【问题标题】:Replace String from file In python?在python中替换文件中的字符串?
【发布时间】:2019-01-20 21:25:45
【问题描述】:

我有一个包含多个电话号码的文件。 现在我想将此文件的任何行转换为 VCF 文件。 因此,首先我为具有字符串“THISNUMBER”的 VCF 文件定义了 e 模板模型 我想打开文件(那有电话号码)并将那行替换为模板模型(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 中是否缺少open()?

标签: python python-3.x replace vcf-vcard


【解决方案1】:

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

问题可能是您忘记在您的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

【讨论】:

    【解决方案2】:

    改变

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

    到

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

    【讨论】:

      猜你喜欢
      • 2015-11-24
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      • 2014-07-08
      • 2023-03-21
      • 2016-04-01
      • 1970-01-01
      相关资源
      最近更新 更多