python中csv文件通过什么表示字符_python – 如果行包含CSV文件中的字符串,则删除该行...
我在刪除包含一列中的字符串的文本文件中的行時遇到問題.到目前為止,我的代碼無法刪除該行,但它能夠讀取文本文件并將其作為CSV文件保存到單獨的列中.但這些行不會被刪除.
這就是該列中的值如下所示:
Ship To or Bill To
------------------
3000000092-BILL_TO
3000000092-SHIP_TO
3000004000_SHIP_TO-INAC-EIM
還有20多列和50,000k多行.所以基本上我試圖刪除包含字符串’INAC’或’EIM’的所有行.
import csv
my_file_name = "NVG.txt"
cleaned_file = "cleanNVG.csv"
remove_words = ['INAC','EIM']
with open(my_file_name, 'r', newline='') as infile, \
open(cleaned_file, 'w',newline='') as outfile:
writer = csv.writer(outfile)
for line in csv.reader(infile, delimiter='|'):
if not any(remove_word in line for remove_word in remove_words):
writer.writerow(line)
最佳答案 這里的問題是csv.reader對象將文件的行作為單個列值的列表返回,因此“in”測試檢查該列表中的任何單個值是否等于remove_word.
快速修復就是嘗試
if not any(remove_word in element
for element in line
for remove_word in remove_words):
因為如果行中的任何字段包含任何remove_words,則為true.
總結
以上是生活随笔為你收集整理的python中csv文件通过什么表示字符_python – 如果行包含CSV文件中的字符串,则删除该行...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python转cython_Cython
- 下一篇: .pyc文件_python专题shuti