Python 找到一条线并替换它
我有一个这样的文件Python 找到一条线并替换它,python,Python,我有一个这样的文件 Dog, fun= it is always, ok cat, run = it is always, ok 我想将第一个总是更改为不总是,将第二个总是更改为可以总是 我的问题是如何告诉python按照我的要求更改相应的短语 我的代码 def read_and_replace(filepath,newfilename,replacedictionary): os.chdir(filepath) file = open(filename, "r")
Dog, fun= it is always, ok
cat, run = it is always, ok
我想将第一个总是
更改为不总是
,将第二个总是
更改为可以总是
我的问题是如何告诉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'
但是,一旦我想将一行更改为“it always”,下一行更改为“can always”不清楚您究竟何时要替换文本,但是替换很容易,只需使用
string.replace()
:
你可以用
完整示例:
假设您想更改第一行,并且只更改那一行,这就是我得到的:
>>> 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
这样我就把你的文件做好了。然后我声明了一个空字符串,它将构成我们的新文件。我打开原始文件并声明了一个计数器。我浏览了每一行,如果我们正在阅读第一行,则替换了文本。然后计数器递增,表示我们不再在第一行。然后我们对第二行进行下一次替换
然后我打开一个新文件并读入该文件(或者,您可以打开原始文件并写入以完全替换所有内容)。最后一位将重新读取新文件,以确保所有内容都已就绪
编辑为包含始终都可以。@令人印象深刻的云雀我想,伟大的思想都是一样的:)
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
>>> 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