我无法删除一列中包含字符串的文本文件中的行。到目前为止,我的代码无法删除该行,但它能够读取文本文件并将其作为 CSV 文件保存到单独的列中。但行没有被删除。
这是该列中的值的样子:
Ship To or Bill To
------------------
3000000092-BILL_TO
3000000092-SHIP_TO
3000004000_SHIP_TO-INAC-EIM
Run Code Online (Sandbox Code Playgroud)
还有 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)
Run Code Online (Sandbox Code Playgroud)
这里的问题是该csv.reader对象将文件的行作为单个列值的列表返回,因此“in”测试正在检查该列表中的任何单个值是否等于 a remove_word。
一个快速的解决方法是尝试
if not any(remove_word in element
for element in line
for remove_word in remove_words):
Run Code Online (Sandbox Code Playgroud)
因为如果该行中的任何字段包含任何remove_words.
| 归档时间: |
|
| 查看次数: |
7970 次 |
| 最近记录: |