简体   繁体   English

从python中的列表替换文件中的字符串

[英]replacing strings in files from list in python

So I need to find all files with certain extension in this case .txt . 所以我需要在这种情况下查找具有特定扩展名的所有文件.txt Then I must open all these files and change certain string with another string... and here i'm stuck. 然后我必须打开所有这些文件并用另一个字符串更改某些字符串......在这里我被卡住了。

here is my code: 这是我的代码:

import os, os.path

find_files=[]

for root, dirs, files in os.walk("C:\\Users\\Kevin\\Desktop\\python programi"):
for f in files:
    fullpath = os.path.join(root, f)
    if os.path.splitext(fullpath)[1] == '.txt':
        find_files.append(fullpath)
for i in find_files:
    file = open(i,'r+')
    contents = file.write()
    replaced_contents = contents.replace('xy', 'djla')
    print i

ERROR mesage: 错误消息:

line 12, in <module>
    contents = file.write()
TypeError: function takes exactly 1 argument (0 given)

i know that there is misssing an argument but which argument should I use? 我知道有一个错误的争论,但我应该使用哪个论点? i think it would be better if i change the code from for i in find files: down any advice? 我认为如果for i in find files:更改i的代码会更好for i in find files:任何建议?

我认为你的意思是使用file.read()而不是file.write()

Not sure if you're just trying to print out the changes or if you want to actually rewrite them into the file, in which case you could just do this: 不确定您是否只是尝试打印更改,或者是否要将它们实际重写到文件中,在这种情况下您可以这样做:

for i in find_files:
    replaced_contents = ""
    contents = ""
    with open(i, "r") as file:
        contents = file.read()
        replaced_contents = contents.replace('xy', 'djla')
    with open(i, "w") as file:
        file.write(replaced_contents)
    print i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM