0

私はpythonが初めてで、バージョン2.7を使用しています

その行の残りの部分を埋めるstringa を使用して、ファイル内を置き換えたいと思います。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')

JF Sebastianの最新コード

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'

助言がありますか?

4

2 に答える 2

0

私はついに答えを見つけました...

Nightly.py 実行前の test1.txt:

blah
blah
This is a first string
blah
blah

ところで、タブはメモ帳++でコードに違いをもたらします

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
于 2013-04-12T06:06:51.927 に答える