[英]Python CSV Writer leave a empty line at the end of the file
下面的代碼在 txt 文件的末尾留下一個空的白線。 我怎么能不讓 writerows 不終止最后一行?
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()
首先,由於您使用with open as myFile
您不需要myFile.close()
,當您刪除縮進時會自動完成。
其次,如果您願意在程序中添加另一部分,您可以簡單地編寫一些刪除最后一行的內容。 Strawberry制作了一個示例(略有改動):
with open(fname) as myFile:
lines = myFile.readlines()
with open(fname, "w") as myFile:
myFile.writelines([item for item in lines[:-1]])
注意 'w' 參數是如何清除文件的,所以我們需要打開文件兩次,一次是讀,一次是寫。
我也相信,您可以使用myFile.write
,它不添加換行符。 使用它的一個例子是:
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))
但是,這僅在您擁有多維數組時才有效,並且可能應該避免。
我找不到適用於 python 3 和我的情況的答案,所以這是我的解決方案:
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)
我很欣賞這是一個舊的請求,但我在尋找相同的解決方案時偶然發現了它。 我最終閱讀了csv 文檔本身中的答案,發現 csv.writer 有一個lineterminator
格式化參數,默認為\\r\\n
,給出了我們都不想要的新行。
作為一種解決方案,我在代碼中添加了格式參數newline=''
並且它運行良好(在下面的原位)。
with open(fname, 'wb') as myFile:
# Start the CSV Writer
wr = csv.writer(myFile, delimiter=',', dialect='excel', lineterminator='')
wr.writerows(rows)
感謝wfgeo
其中一種解決方案是這樣工作的。 雖然它需要os
庫,但它使生活更輕松:
import csv
import os
with open(fileName, 'w', newline='') as f:
writer = csv.writer(f, delimiter=';', dialect='excel')
for row in rows:
row = rows[0].values()
writer.writerow(row)
f.seek(0, os.SEEK_END)
f.seek(f.tell()-2, os.SEEK_SET)
f.truncate()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.