问题
the following code leave a empty white line at the end of the txt file. how can i not have the writerows not terminate the last line?
with open(fname, 'wb') as myFile:
# Start the CSV Writer
wr = csv.writer(myFile, delimiter=',', dialect='excel')
wr.writerows(rows)
# Close the file.
myFile.close()
回答1:
Firstly, since you are using with open as myFile
you don't need myFile.close()
, that is done automatically when you remove the indent.
Secondly, if you are willing to add another part to your program, you could simply write something that removes the last line. An example of this is made by Strawberry (altered slightly):
with open(fname) as myFile:
lines = myFile.readlines()
with open(fname, "w") as myFile:
myFile.writelines([item for item in lines[:-1]])
Note how the 'w' parameter will clear the file, so we need to open the file twice, once to read and once to write.
I also believe, you are able to use myFile.write
, which doesn't add newlines. An example of using this would be:
with open(fname, 'wb') as myFile:
wr = csv.writer(myFile, delimiter=',', dialect='excel')
lines = []
for items in rows:
lines.append(','.join(items))
wr.write('\n'.join(lines))
This however will only work if you have a multi-dimensional array, and should probably be avoided.
回答2:
I couldn't find an answer that will work in python 3 and also for my case so here is my solution:
def remove_last_line_from_csv(filename):
with open(filename) as myFile:
lines = myFile.readlines()
last_line = lines[len(lines)-1]
lines[len(lines)-1] = last_line.rstrip()
with open(filename, 'w') as myFile:
myFile.writelines(lines)
来源:https://stackoverflow.com/questions/29335614/python-csv-writer-leave-a-empty-line-at-the-end-of-the-file