我有一个像这样的文件
Dog, fun= it is always, ok
cat, run = it is always, ok
我想将第一个it is always
更改为not always
,将第二个it is always
更改为can be always
。
我的问题是如何告诉python更改我希望它的相应短语
我的代码
def read_and_replace(filepath,newfilename,replacedictionary):
os.chdir(filepath)
file = open(filename, "r")
fileContent = file.read()
file.close()
for word in replacedictionary:
fileContent=fileContent.replace(word,replacedictionary[word])
output = open(filename, "w")
output.write(fileContent)
output.close()
在此之后,我在字典中创建了一个带有输入文件的字典,但是不知道如何到达特定的行并按照我希望的方式更改文本。我也是编程的新手,所以坚持这个。
这个被替换的字符串用我给出的一行来改变这两行。例如:
replacedictionary['it is always']='not always'
但是一旦我想改变一行作为"它总是"并且下一行作为"可以始终"
答案 0 :(得分:1)
目前还不清楚何时想要替换文字,但更换很简单,只需使用string.replace()
:
for line in lines:
line.replace('it is always, ok','not always')
答案 1 :(得分:0)
您可以使用string.replace()
完整示例:
with open('my_file.txt') as f:
lines = f.readlines()
lines[0] = lines[0].replace('it is always', 'not always')
lines[1] = lines[1].replace('it is always', 'can be always')
print '\n'.join(lines)
>> Dog, fun= not always, ok
>> cat, run = can be always, ok
答案 2 :(得分:0)
假设您想要更改第一行,只有那条线就是我得到的:
>>> with open("test.txt", "w") as file:
file.write("Dog, fun= it is always, ok\ncat, run = it is always, ok")
54
>>> newFile = ""
>>> with open("test.txt", "r") as file:
counter = 0
for line in file:
if counter == 0:
newFile = newFile + line.replace("it is always", "not always")
elif counter == 1:
newFile = newFile + line.replace("it is always", "can be always")
else:
newFile = newFile + line
counter += 1
print(newFile)
Dog, fun= not always, ok
cat, run = it is always, ok
>>> with open("newtest.txt", "w")as newerfile:
newerfile.write(newFile)
52
>>> with open("newtest.txt", "r") as file:
for line in file:
print(line)
Dog, fun= not always, ok
cat, run = it is always, ok
这样我就制作了你的文件。然后我宣布一个空字符串,它将形成我们的新文件。我打开原始文件并宣布了一个计数器。我浏览了每一行,在我们阅读第一行的情况下,替换了文本。然后递增计数器以显示我们不再在第一行。然后我们为第二行做下一次替换。
然后我打开一个新文件并读入该文件(或者你可以打开原始文件并写入以完全替换所有内容)。最后一位重新读取新文件以确保一切就绪。
编辑包含可以永远。