从 python 中的文件替换字符串?

Replace String from file In python?

我有一个包含几个 Phone 号码的文件。 现在我想将该文件的任何行转换为 VCF 文件。 因此,首先我为具有字符串 "THISNUMBER" 的 VCF 文件定义了 e 模板模型 我想打开文件(有 phone 个数字)并将这些行替换为模板模型 (THISNUMBER)

我写了这个Python代码:

template = """BEGIN:VCARD
VERSION:3.0
N:THISNUMBER;;;
FN:THISNUMBER
TEL;TYPE=CELL:THISNUM
END:VCARD"""

inputfile=open('D:/xxx/lst.txt','r')
counter=1
for thisnumber in inputfile:
    thisnumber=thisnumber.rstrip()
    output=template.replace('THISNUMBER',thisnumber)
    outputFile=('D:/xxx/vcfs/%05i.vcf' % counter,'w')
    outputFile.write(output)
    output.close
    print ("writing file %i") % counter
    counter +=1
    inputfile.close()

但我给出了这个错误:

Traceback (most recent call last):
 File "D:\xxx\a.py", line 16, in <module>
 outputFile.write(output)
 AttributeError: 'tuple' object has no attribute 'write'

改变

outputFile=('D:/xxx/vcfs/%05i.vcf' % counter,'w')

outputFile=open('D:/xxx/vcfs/%05i.vcf' % counter,'w')

我会写一个完整的答案,因为我想解决你的代码风格,如果可以的话。

问题很可能是您忘记在 outputFile 上调用 open()。但是,让我向您介绍一种在 Python 中处理文件的好方法。这样你甚至不必记得调用 close()。这一切都是通过上下文管理器完成的。当 with 语句退出时文件关闭。

template = """BEGIN:VCARD
VERSION:3.0
N:THISNUMBER;;;
FN:THISNUMBER
TEL;TYPE=CELL:THISNUM
END:VCARD"""

with open('D:/xxx/lst.txt', 'r') as inputfile:
    counter = 1
    for number in inputfile:
        number = number.rstrip()
        output = template.replace('THISNUMBER', number)
        with open('D:/xxx/vcfs/%05i.vcf' % counter, 'w') as outputFile:
            outputFile.write(output)

        print('writing file %i' % counter)
        counter += 1