我刚刚开始使用 Python 3.4.2 并尝试查找并替换 csv 文件中的文本。
在详细信息中,Input.csv
文件包含以下行:
0,0,0,13,.\New_Path-1.1.12\Impl\Appli\Library\Module_RM\Code\src\Exception.cpp
0,0,0,98,.\Old_Path-1.1.12\Impl\Appli\Library\Prof_bus\Code\src\Wrapper.cpp
0,0,0,26,.\New_Path-1.1.12\Impl\Support\Custom\Vital\Code\src\Interface.cpp
0,0,0,114,.\Old_Path-1.1.12\Impl\Support\Custom\Cust\Code\src\Config.cpp
我维护了要在名为 list.csv
的其他文件中搜索的字符串
Module_RM
Prof_bus
Vital
Cust
现在我需要遍历 Input.csv
的每一行,并将最后一列替换为匹配的字符串。
所以我的最终结果应该是这样的:
0,0,0,13,Module_RM
0,0,0,98,Prof_bus
0,0,0,26,Vital
0,0,0,114,Cust
我将输入文件的第一行作为列表读取。所以我需要替换的文本出现在 line[4]
中。我正在读取 list.csv
文件中的每个模块名称,并检查 line[4]
中是否存在任何匹配的文本。我无法使 if
条件 true
。如果搜索不正确,请告诉我。
import csv
import re
with open("D:\\My_Python\\New_Python_Test\\Input.csv") as source, open("D:\\My_Python\\New_Python_Test\\List.csv") as module_names, open("D:\\My_Python\\New_Python_Test\\Final_File.csv","w",newline="") as result:
reader=csv.reader(source)
module=csv.reader(module_names)
writer=csv.writer(result)
#lines=source.readlines()
for line in reader:
for mod in module_names:
if any([mod in s for s in line]):
line.replace(reader[4],mod)
print ("YES")
writer.writerow("OUT")
print (mod)
module_names.seek(0)
lines=reader
请指导我完成这项任务。
感谢您的支持!
最佳答案
我终于成功解决了这个问题!
下面的代码运行良好!
import csv
with open("D:\\My_Python\\New_Python_Test\\Input.csv") as source, open("D:\\My_Python\\New_Python_Test\\List.csv") as module_names, open("D:\\My_Python\\New_Python_Test\\Final_File.csv","w",newline="") as result:
reader=csv.reader(source)
module=csv.reader(module_names)
writer=csv.writer(result)
flag=False
for row in reader:
i=row[4]
for s in module_names:
k=s.strip()
if i.find(k)!=-1 and flag==False:
row[4]=k
writer.writerow(row)
flag=True
module_names.seek(0)
flag=False
感谢尝试解决问题的人!如果您有任何更好的编码实践,请分享!
祝你好运!
关于csv - 使用 Python 搜索并替换 CSV 文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31880939/