Jun-02-2018, 02:06 PM
Hi all,
I am having problems writing seperate data entiries into a file. The code (listed below) keeps on appending the data into one long string, so I cannot read the data item back into a variable.
e.g if I enter 5 data values (1 [return] 2 [return] 3 [return] 4 [return] 5[return]} instead of writing the values as 1,2,3,4,5 into the file, it writes it as a string 1\n2\n3\n4\n5\n. So when I try to read the first value into a variable, I get 1\n2\n3\n4\n5\n instead of 1. I am trying to get the program to write and read back each number individually.
I have even tried opening and closing the file with each data input, hoping that this would give me individual entries in the file, but this did not work either
I hope this makes sense.
Thanks in advance
I am having problems writing seperate data entiries into a file. The code (listed below) keeps on appending the data into one long string, so I cannot read the data item back into a variable.
e.g if I enter 5 data values (1 [return] 2 [return] 3 [return] 4 [return] 5[return]} instead of writing the values as 1,2,3,4,5 into the file, it writes it as a string 1\n2\n3\n4\n5\n. So when I try to read the first value into a variable, I get 1\n2\n3\n4\n5\n instead of 1. I am trying to get the program to write and read back each number individually.
I have even tried opening and closing the file with each data input, hoping that this would give me individual entries in the file, but this did not work either
I hope this makes sense.
Thanks in advance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#Appending text to file for i in range ( 5 ): new_file = open ( "test.txt" ,mode = "a+" ,encoding = "utf-8" ) er = input ( "Enter some text:" ) rt = er + "\n" new_file.write(rt) new_file.close() #Reading data from test.txt new_file = open ( "test.txt" , "r" ) #for line in new_file: for line in range ( 5 ): x = new_file.read() print (x) new_file.close() |