python:用另一个文件的内容替换文件中的字符串

python:用另一个文件的内容替换文件中的字符串,python,Python,我有两个文件src和dest #cat src lundi,mardi,mercredi,jeudi # cat dest janvier fevrier mars avril mai juillet aout septembre octobre 对于python,我想用文件src的内容替换文件dest中的字符串“mai”。结果将是 # cat dest janvier fevrier mars avril lundi,mardi,mercredi,jeudi juil

我有两个文件src和dest

#cat src
lundi,mardi,mercredi,jeudi

# cat dest
janvier fevrier 
mars avril mai  
juillet aout  
septembre octobre  
对于python,我想用文件src的内容替换文件dest中的字符串“mai”。结果将是

# cat dest
janvier fevrier  
mars avril lundi,mardi,mercredi,jeudi  
juillet aout  
septembre octobre  
谢谢你的帮助


我尝试了那些脚本,但它是负面的

1-

2-

  • 打开src和dest进行读取
  • 将其内容读入变量
  • 关闭打开的文件。(如果您知道这是什么,可以使用上下文管理器…)
  • 将dest中的“mai”替换为src的内容(使用
    string.Replace
  • 重新打开dest进行写作
  • 写入新数据
  • *微笑
  • *可选,尽管深受鼓励

    谢谢大家,
    with open("src",'r') as file:
        src = file.read()
        file.close()
    
    with open("dest",'r') as file:
        dest = file.read()
        file.close()
    
    dest.replace('mai',src)
    
    with open("dest",'w') as file:
        file.write(dest)
        file.close()
    
    我解决了我的问题。这是我的主张

    with open("src","r") as file1:
         src = file1.read()
         src = src.rstrip()
         with open("dst","r") as file2:
             dst=file2.read()
             resultat=dst.replace('mai',src)
             with open("dst","w") as file2:
                 file2.write(resultat)
    

    欢迎来到堆栈溢出!我们鼓励你这样做。如果您有,请将其添加到问题中-如果没有,请先研究并尝试您的问题,然后再回来。您可以在此处阅读python字符串的文档*我尝试了您的脚本,但文件dest是相同的,它没有更改,但在屏幕上输出结果良好。*写入模式无效无需
    文件。如果使用上下文管理器,请关闭
    。另外,
    file
    是python中的内置类型,虽然可以将其用作变量名,但使用不同的名称可能更安全。最后(也是最重要的),这个问题被标记为家庭作业。仅仅回答家庭作业问题通常是不可取的。(指导解决方案更有用)我尝试了这些脚本,但它是负1-导入os,sys,open(“src”,“r”)作为s:open(“dst”,“w”)作为d:for ligne,在dst:sligne=ligne.rstrip().split(“”)中对于sline中的n:sline=mai dst.str.replace(“mai”,“src”)2-d=open(“dst”,“w”)s=open(“src”,“r”)data=s.read()s.close()对于dst中的n:data=data.replace(“mai”,“s”)d.write(data)d.close()@user1662958——正如我前面所说的,在问题中添加这段代码。在这里的注释中查看它,是不可能阅读的(在python中,空格很重要)。要编辑原始问题,只需单击其下方的“编辑”链接,即可添加所需信息。
    with open("src",'r') as file:
        src = file.read()
        file.close()
    
    with open("dest",'r') as file:
        dest = file.read()
        file.close()
    
    dest.replace('mai',src)
    
    with open("dest",'w') as file:
        file.write(dest)
        file.close()
    
    with open("src","r") as file1:
         src = file1.read()
         src = src.rstrip()
         with open("dst","r") as file2:
             dst=file2.read()
             resultat=dst.replace('mai',src)
             with open("dst","w") as file2:
                 file2.write(resultat)