Python 替换文件中的特定值

Python 替换文件中的特定值,python,string,file,Python,String,File,我试图用一个值替换文件中的一个值。一切正常,但当我在文件完成后查看它时,没有任何变化。我能用什么做这个 文件内容: 22102014,1646,1,0,1848,3559,5,0,1848,0,0,1,0,1,1664,4997,2257,9,0,1664 我只想将tird值从1更改为0 以下是我的代码: # Read in the file with open("datafile", 'r') as f: data = f.read() # Replace the targ

我试图用一个值替换文件中的一个值。一切正常,但当我在文件完成后查看它时,没有任何变化。我能用什么做这个

文件内容:

22102014,1646,1,0,1848,3559,5,0,1848,0,0,1,0,1,1664,4997,2257,9,0,1664    
我只想将tird值从
1
更改为
0

以下是我的代码:

# Read in the file
with open("datafile", 'r') as f:
    data = f.read()

# Replace the target string
data.replace('1', '0')

# Write the file out again
with open("datafile", 'w') as f:
    f.write (data)    

是否可以使用
str.replace

您在问题中说过要用
0
替换第三个值。如果是这样,则
str.replace
不是您想要使用的,因为它将每个
1
替换为
0

相反,您可以使用以下选项:

# Read in the file
with open("datafile", 'r') as f:
    data = f.read()

lst = data.split(',')   # Split data on , with str.split
lst[2] = '0'            # Replace the value at index 2 (the third value)
data = ','.join(lst)    # Rebuild the string with str.join

# Write the file out again
with open("datafile", 'w') as f:
     f.write(data)

字符串方法
str.split
str.join
都有文档记录。

您需要分配结果,
data=data.replace(…)
;字符串是不可变的。但是您想替换所有的零吗?