[英]How should I replace parts from a text file through Python?
Okay, so here's the deal, folks: 好的,伙计们,这是交易:
I've been experimenting with Python(3.3), trying to create a python program capable of generating random names for weapons in a game and replacing their old names, which are located inside a text file. 我一直在尝试使用Python(3.3),试图创建一个python程序,该程序能够为游戏中的武器生成随机名称,并替换旧名称(位于文本文件中)。 Here's my function: 这是我的功能:
def ModifyFile(shareddottxt):
global name
a = open(str(shareddottxt) , 'r')
b = a.read()
namefix1 = '''SWEP.PrintName = "'''
namefix2 = '''" //sgaardname'''
name1 = b.find(namefix1) + len(namefix1)
name2 = b.find(namefix2, name1)
name = name + b[name1:name2] ## We got our weapon's name! Let's add the suffix.
c = open((shareddottxt + ".lua"), 'r+')
for line in b:
c.write(line.replace(name, (name + namesuffix)))
c.close()
a.close
As you can see, I first open my text file to find the weapon's name. 如您所见,我首先打开我的文本文件以找到武器的名称。 After that, I try to create a new file and copy the contents from the old one, while replacing the weapon's name for (name + namesuffix). 之后,我尝试创建一个新文件并从旧文件中复制内容,同时将武器名称替换为(名称+名称后缀)。 However, after calling the function, I get nothing. 但是,调用该函数后,我什么也没得到。 No file whatsoever. 没有任何文件。 And even if I DO add the file to the folder manually, it does not change. 即使我确实将文件手动添加到文件夹,它也不会更改。 At all. 完全没有
Namesuffix is generated through another function early on. 名称后缀是通过早期的另一个函数生成的。 It is saved as a global var. 将其另存为全局变量。
Also, my text file is huge, but the bit I'm trying to edit is: 另外,我的文本文件很大,但是我要编辑的位是:
SWEP.PrintName = "KI Stinger 9mm" //sgaardname
The expected result: 预期结果:
SWEP.PrintName = "KI Stinger 9mm NAMESUFFIX" //sgaardname
Where did I mess up, guys? 伙计们,我在哪里弄糟?
Something like this is more pythonic. 像这样的东西更pythonic。
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r+') as file:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
file.seek(0)
file.write(new_lines)
If you don't want to replace that file 如果您不想替换该文件
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r') as file, open(filename + ".temp", 'w') as temp:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
temp.write(new_lines)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.