Python CSV Writer在文件末尾留空行 [英] Python CSV Writer leave a empty line at the end of the file
问题描述
以下代码在txt文件的末尾保留空白行。我怎么不能让写行不终止最后一行?
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()
推荐答案
首先,由于您使用的是,并且以myFile形式打开
,因此您不需要 myFile.close()
,该操作会在您删除缩进。
Firstly, since you are using with open as myFile
you don't need myFile.close()
, that is done automatically when you remove the indent.
第二,如果您愿意在程序中添加另一部分,则只需编写一些删除最后一行的内容即可。例如草莓(略有更改): / p>
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]])
请注意'w'参数如何清除文件,因此我们需要打开文件两次,一次读取一次,一次写入。
Note how the 'w' parameter will clear the file, so we need to open the file twice, once to read and once to write.
我也相信,您可以使用 myFile.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.
这篇关于Python CSV Writer在文件末尾留空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!