[英]Finding and replacing multiple strings in multiple files in python
I'm trying to go through a bunch of files in a directory and find and replace a list of strings and write them to the same file. 我正在尝试浏览目录中的一堆文件,查找并替换字符串列表,然后将它们写入同一文件。 When I run the scripts all the files in the directory turn out blank! 当我运行脚本时,目录中的所有文件都变成空白! What am I doing wrong here? 我在这里做错了什么?
os.chdir("Resources/maps_sideScrolling/HD")
replacements = {'tilewidth=\"16\"':'tilewidth=\"32\"', 'tileheight=\"16\"':'tileheight=\"32\"', '.png':'-hd.png'}
for files in os.listdir("."):
if files.endswith("-hd.tmx"):
fo = open(files, "rU")
fw = open(files, "w")
for line in fo:
for src, target in replacements.iteritems():
line = line.replace(src, target)
fw.write(line)
fo.close();
fw.close();
If you want to overwrite the file you can use below code: 如果要覆盖文件,可以使用以下代码:
os.chdir("Resources/maps_sideScrolling/HD")
replacements = {'tilewidth=\"16\"':'tilewidth=\"32\"', 'tileheight=\"16\"':'tileheight=\"32\"', '.png':'-hd.png'}
for files in os.listdir("."):
if files.endswith("-hd.tmx"):
fo = open(files, "rU+")
text = fo.read()
for src, target in replacements.iteritems():
text = text.replace(src, target)
fo.seek(0)
fo.write(text)
fo.truncate()
fo.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.