text_file = open("new.txt", "r") lines = text_file.readlines() for line in lines: var1, var2 = line.split(","); myfile = open('xyz.txt', 'w') myfile.writelines(var1) myfile.close() text_file.close()
I have 10 lines of text in new.txt like Adam:8154
, George:5234
, and so on. Now I want a text file which contains only the names. xyz.txt
must contain Adam
, George
, and so on. The above code leaves me with the 10th name only.
How to have all the 10 names in a single text file?
To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.
That is because you are opening , writing and closing the file 10 times inside your for loop
myfile = open('xyz.txt', 'w') myfile.writelines(var1) myfile.close()
You should open and close your file outside for loop.
myfile = open('xyz.txt', 'w') for line in lines: var1, var2 = line.split(","); myfile.write("%s\n" % var1) myfile.close() text_file.close()
You should also notice to use write and not writelines.
writelines
writes a list of lines to your file.
Also you should check out the answers posted by folks here that uses with
statement. That is the elegant way to do file read/write operations in Python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With