如何使用带有外卡的python替换文件的一行

时间:2013-04-08 02:19:28

标签: python-2.7 windows-7-x64

我是python的新手,使用的是2.7版

我想使用填充该行其余部分的string替换文件中的wild card。这是我到目前为止所拥有的......

这样可以将文件字符串更改为second string

if line == 'This = first string':
    line = 'This = second string'

这不起作用,文件字符串将保持为first string

if line == 'This = *':
    line = 'This = second string'

完整脚本:

import sys
import shutil
import os
import re

#Assigns tf as a tmp file with the module for appending and writing, and creating the file if it does not exist.
tf = open('tmp', 'a+')

#Assigns f as test.txt
with open('test1.txt') as f:
#Reads the line in the test1.txt file
    for line in f.readlines():
#Checks for the line condition
        if line == 'This = *':
#Sets the new line condition
            line = 'This = second string'
#Replaces the line withe the new build path
        tf.write(line)
#Closes the test2.txt file
f.close()
tf.close()
#Copies the changes from the tmp file and replaces them into the test2.txt
shutil.copy('tmp', 'test2.txt')
#Removies the tmp file from the computer
os.remove('tmp')

J.F的最新代码。塞巴斯蒂安

test2.txt内容:

blah
This = first string

testing2.py内容:

import os
from tempfile import NamedTemporaryFile

prefix = "This = "
path = 'test2.txt'  
dirpath = os.path.dirname(path)
with open(path) as input_file:
    with open(path+".tmp", mode="w") as tmp_file:
        for line in input_file:
            if line.startswith(prefix):
                line = prefix + "second string\n"
            tmp_file.write(line)
        tmp_file.delete = False
os.remove(path)
os.rename(tmp_file.name, path)

错误讯息:

C:\Users\james>testing2.py
Traceback (most recent call last):
  File "C:\Users\james\testing2.py", line 13, in <module>
    tmp_file.delete = False
AttributeError: 'file' object has no attribute 'delete'

任何建议?

2 个答案:

答案 0 :(得分:1)

替换以前缀开头的行:

prefix = "This = "
if line.startswith(prefix):
    line = prefix + "second string"

如果文件是包含key = value行的配置文件,那么您也可以使用line.partition() method, ConfigParser module或正则表达式(在更复杂的情况下)替换值:

import re
# ...
line = re.sub(r"^This\s*=.*$", "This = second string", line)

替换文件中的行;你可以使用fileinput module or just write to a temporary file (tempfile.NamedTemporaryFile) and rename it at the end

#!/usr/bin/env python
import os
from tempfile import NamedTemporaryFile

prefix = "This = "
path = 'test1.txt'  
dirpath = os.path.dirname(path)
with open(path) as input_file:
    with NamedTemporaryFile(mode="w", dir=dirpath) as tmp_file:
        for line in input_file:
            if line.startswith(prefix):
                line = prefix + "second string\n"
            tmp_file.write(line)
        tmp_file.delete = False
os.remove(path)
os.rename(tmp_file.name, path)

答案 1 :(得分:0)

我终于找到了答案......

在执行Nightly.py之前

test1.txt:

blah
blah
This is a first string
blah
blah

BTW标签使用notepad ++

对代码产生影响
import sys
import os
import re
import shutil

tf = open('tmp', 'a+')

with open('test1.txt') as f:
    for line in f.readlines():
        build = re.sub ('This is.*','This is a second string',line)
        tf.write(build)
tf.close()
f.close()
shutil.copy('tmp', 'test1.txt')
os.remove('tmp')
执行Nightly.py后

test1.txt:

blah
blah
This is a second string
blah
blah