Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:替换文件中的多个单词_Python - Fatal编程技术网

python:替换文件中的多个单词

python:替换文件中的多个单词,python,Python,我有一个文件apple.py,它有单词apple和apple。 还有一个空白文件pear.py 我想阅读apple.py的内容并将其写入pear.py,然后修改 apple到pear, Apple到Pear 我是这样做的: def modify_city(): with open('city.py', 'r+') as f: read_data = f.read() with open('beijing', 'w') as f: f.write(r

我有一个文件
apple.py
,它有单词
apple
apple
。 还有一个空白文件
pear.py

我想阅读
apple.py
的内容并将其写入
pear.py
,然后修改
apple
pear
Apple
Pear

我是这样做的:

def modify_city():
    with open('city.py', 'r+') as f:
        read_data = f.read()
    with open('beijing', 'w') as f:
        f.write(read_data.replace('city', 'beijing'))  #it works
        f.write(read_data.replace('City', 'Beijing'))  #it doesn't work
问题:

在代码中,第一个
replace()
有效,但第二个
replace()
无效。我该怎么办?

代码无效的原因是:

  • 将整个数据写入文件两次
  • str.replace()。通过做

    f.write(read_data.replace('city', 'beijing'))
    
    第一次,您打印到文件
    read\u data
    ,替换为
    'city'
    'beijing'
    ,但您不将更改保存到
    read\u data
    。第二次当你这样做的时候

    f.write(read_data.replace('City', 'Beijing'))
    
    不会保存上一次替换,因此会替换原始字符串

  • 话虽如此,您有两种选择:

    def modify_city():
        with open('city.py', 'r+') as f:
            read_data = f.read()
        with open('beijing.py', 'w') as f:
            f.write(read_data.replace('city', 'beijing').replace('City', 'Beijing'))
    


    代码不起作用的原因是:

  • 将整个数据写入文件两次
  • str.replace()。通过做

    f.write(read_data.replace('city', 'beijing'))
    
    第一次,您打印到文件
    read\u data
    ,替换为
    'city'
    'beijing'
    ,但您不将更改保存到
    read\u data
    。第二次当你这样做的时候

    f.write(read_data.replace('City', 'Beijing'))
    
    不会保存上一次替换,因此会替换原始字符串

  • 话虽如此,您有两种选择:

    def modify_city():
        with open('city.py', 'r+') as f:
            read_data = f.read()
        with open('beijing.py', 'w') as f:
            f.write(read_data.replace('city', 'beijing').replace('City', 'Beijing'))
    


    您将整个读取数据写入文件两次

    read_data = read_data.replace('city','beijing')
    read_data = read_data.replace('City','Beijing')
    f.write(read_data)
    

    您将整个读取数据写入文件两次

    read_data = read_data.replace('city','beijing')
    read_data = read_data.replace('City','Beijing')
    f.write(read_data)