The main problem was that you were opening/closing files repeatedly inside your loop.
Try this approach:
with open('new.txt') as text_file, open('xyz.txt', 'w') as myfile:
for line in text_file:
var1, var2 = line.split(",");
myfile.write(var1+'\n')
We open both files at once and because we are using with
they will be automatically closed when we are done (or an exception occurs). Previously your output file was repeatedly openend inside your loop.
We are also processing the file line-by-line, rather than reading all of it into memory at once (which can be a problem when you deal with really big files).
Note that write()
doesn't append a newline ('\n'
) so you'll have to do that yourself if you need it (I replaced your writelines()
with write()
as you are writing a single item, not a list of items).
When opening a file for r
read, the 'r'
is optional since it's the default mode.