-5
newfile = open("Student Data.txt","w")
    with open("Student Data.txt") as a_file:
            data = a_file.readlines()

    data[1] = username + " " + password + "\n"

    with open("Student Data.txt", "w") as a_file:
            a_file.writelines(data)

    input()

i have created username and password with a input statement and and a int input for the age. If anyone can help me write this to a .txt file i would help me massively.

Rakesh
  • 81,458
  • 17
  • 76
  • 113

2 Answers2

0

I would firstly advise using the file.read function over file.readlines, basically because it prevents you having to split the text any more times than you have to. Then you should use the .split function with the appropriate splitting character (usually space).

And so my take on your code was this: This next section is about accessing and reading the file.

newfile= open("Student Data.txt", "r")
fileContents=newFile.read()
splitContents=fileContents.split("\n")
for Lines in splitContents:
    print(Lines)

This section is about taking the inputs (without error checks) and writing them into the file.

Writing=open("Student Data.txt", "a")
Username=input("Enter username:\t")
Password=input("Enter password:\t")
Data=Username+" "+Password+"\n"
Writing.write(Data)
0

Your code looks a bit wrong. If you want to have user input and store those inputs in a file, a very basic way of doing this:

# open the file if it exists and replace its contents or create a new one
with open('Student Data.txt', 'w') as user_data:
    user_data.write('username=' + input('username: ')+'\n')
    user_data.write('password=' + input('password: ')+'\n')
    user_data.write('age=' + input('age: ')+'\n')
    user_data.close()

# now if you wanna read it
user_data = open('Student Data.txt', 'r')

for data in user_data:
    print(data)
user_data.close()

In this example you will have each input stored in a new line inside the file.

You can learn more about files reading the documentation: Go To Section 7.2 and 7.2.1 .

R.R.C.
  • 5,439
  • 3
  • 14
  • 19