Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a file in a for loop

Tags:

python

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?

like image 277
h4r5h4 Avatar asked Jun 25 '12 23:06

h4r5h4


People also ask

How do you write to a file in Python?

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.


1 Answers

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

like image 72
pyfunc Avatar answered Oct 01 '22 12:10

pyfunc