Python 3.x 如何替换以特定字符串开头的文件中列表中的第4项?

Python 3.x 如何替换以特定字符串开头的文件中列表中的第4项?,python-3.x,file,replace,Python 3.x,File,Replace,我需要在文件中搜索一个名称,在以该名称开头的行中,我需要替换列表中以逗号分隔的第四项。我已经开始尝试用下面的代码来编程,但是我还没有让它工作 with open("SampleFile.txt", "r") as f: newline=[] for word in f.line(): newline.append(word.replace(str(String1), str(String2))) with open("SampleFile.txt", "w") as f:

我需要在文件中搜索一个名称,在以该名称开头的行中,我需要替换列表中以逗号分隔的第四项。我已经开始尝试用下面的代码来编程,但是我还没有让它工作

with open("SampleFile.txt", "r") as f:
  newline=[]
  for word in f.line(): 
      newline.append(word.replace(str(String1), str(String2)))
with open("SampleFile.txt", "w") as f:
  for line in newline :
      f.writelines(line)

  #this piece of code replaced every occurence of String1 with String 2

f = open("SampleFile.txt", "r")
for line in f:
    if line.startswith(Name):
        if line.contains(String1):
            newline = line.replace(str(String1), str(String2))

  #this came up with a syntax error

你可以提供一些虚拟数据来帮助人们回答你的问题。我建议您备份数据:您可以将编辑的数据保存到新文件中,也可以在处理数据之前将旧文件备份到备份文件夹中(请考虑使用“from shutil import copyfile”和“copyfile(src,dst)”)。否则,如果犯了错误,您可能很容易破坏数据,而无法轻松恢复它们

不能将字符串替换为“newline=line.replace(str(String1),str(String2))”!把“strong”当作你的搜索词,用“Armstrong,Paul,strong,44”这样的一行字——如果你把“strong”换成“weak”,你会得到“Armstrong,Paul,weak,44”

我希望以下代码可以帮助您:

filename     = "SampleFile.txt"
filename_new = filename.replace(".", "_new.")

search_term = "Smith"

with open(filename) as src, open(filename_new, 'w') as dst:

    for line in src:

        if line.startswith(search_term):

            items = line.split(",")
            items[4-1] = items[4-1].replace("old", "new")

            line = ",".join(items)

        dst.write(line)
如果您使用的是csv文件,那么您应该查看

PS My文件包含以下数据(文件中没有文件名!!!):

SampleFile.txt           SampleFile_new.txt

Adams,George,m,old,34    Adams,George,m,old,34
Adams,Tracy,f,old,32     Adams,Tracy,f,old,32
Smith,John,m,old,53      Smith,John,m,new,53
Man,Emily,w,old,44       Man,Emily,w,old,44