简体   繁体   中英

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. 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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