By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,096 Members | 1,568 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,096 IT Pros & Developers. It's quick & easy.

How to send data to specific line in text file

P: 1
Hi,
I'm writing a program - a "social networking site" - where the user is asked to input a message to another user. I can't figure out how to take user input and write it in a specific place in a file containing user data. From the file I convert all the data into a main dictionary.

My file looks something like this:

username1
password1
address1
age1
messages1:
username2
password2
address2
age2
messages2:
username3
password3
address3
age3
messages3:
username4
password4
address4
age4
messages4:
username6
password6
address6
age6
messages6:


From the file I convert all the data into a main dictionary:

Expand|Select|Wrap|Line Numbers
  1. userData = open("data.txt", "r")
  2. temp = userData.read().split("\n")
  3.  
  4.     mainDict = {}
  5.     for i in range(int(len(temp)/6)):
  6.  
  7.         lis = [temp[i*6], temp[i*6+1], temp[i*6+2], temp[i*6+3], temp[i*6+4], temp[i*6+5]]
  8.  
  9.         mainDict[temp[i*6]] = lis
  10.  
  11. userData.close()

Here's the leave a message function that I have atm:

Expand|Select|Wrap|Line Numbers
  1. def leaveMessage(userData):
  2.     saveFile = open("data.txt", "r")
  3.     temp = saveFile.read().split("\n")
  4.  
  5.     mainDict = {}
  6.     for i in range(int(len(temp)/6)):
  7.  
  8.         lis = [temp[i*6], temp[i*6+1], temp[i*6+2], temp[i*6+3], temp[i*6+4],\
  9.               temp[i*6+5]]
  10.  
  11.         mainDict[temp[i*6]] = lis
  12.  
  13.  
  14.     saveFile.close()
  15.  
  16.     recipient = input("Who do you wish to message? ")
  17.     print()
  18.  
  19.     if recipient in mainDict:
  20.         userMessage = input("Please enter your message: ")
  21.         mainDict[recipient][5] = userMessage, "from", userData[0]
  22.  
  23.         newDict = open("data.txt","w")
  24.         # Not sure how to change dictionary and have the text file change
  25.         # accordingly.
  26.  
  27.     else:
  28.         print("User does not exist. Please enter a valid user.")
Any help is much appreciated!
Mar 20 '11 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.