gpt4 book ai didi

python - 在python中查找和替换多个文件中的多个字符串

转载 作者:行者123 更新时间:2023-12-01 05:24:55 26 4
gpt4 key购买 nike

我正在尝试浏览目录中的一堆文件,查找并替换字符串列表并将它们写入同一个文件。当我运行脚本时,目录中的所有文件都变成空白!我在这里做错了什么?

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();

最佳答案

如果您想覆盖文件,可以使用以下代码:

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()

关于python - 在python中查找和替换多个文件中的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com