【问题标题】:Replace a string with another string within a file in Python用Python文件中的另一个字符串替换一个字符串
【发布时间】:2018-05-19 11:04:48
【问题描述】:

将为您提供输入 I 的文件路径、输出 O 的文件路径、字符串 S 和字符串 T。

读取 I 的内容,将每次出现的 S 替换为 T,并将结果信息写入文件 O。

如果 O 已经存在,你应该替换它。

# Get the filepath from the command line
import sys
I= sys.argv[1] 
O= sys.argv[2] 
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')

file2.replace(S, T)

file1.close()
file2.close()

file2= open('O', 'r')

print(file2)

这是我不断收到的错误:

Traceback(最近一次调用最后一次): 文件“write-text-file.py”,第 15 行,在 file2.replace(S, T) AttributeError: '_io.TextIOWrapper' 对象没有属性 'replace'

【问题讨论】:

  • 错误信息非常清楚。你有什么问题?
  • 我想我对它说它没有“替换”属性感到困惑,这是否告诉我这是我正在尝试做的错误命令?
  • open 返回一个文件对象...不是字符串。阅读文档:docs.python.org/3.6/tutorial/inputoutput.html
  • 您需要对 string 对象而不是文件指针执行.replace()。因此,您需要先从file2 检索内容。提示:read()readlines()

标签: python string file replace


【解决方案1】:

这里是代码(修改)

# Get the filepath from the command line
import sys
import re
I= sys.argv[1] 
O= sys.argv[2] 
S= sys.argv[3]
T= sys.argv[4]

# Your code goes here

# open our file for writing
file1= open(I, 'r')
file2= open(O, 'w')
data = file1.read()
data = data.replace(S, T)
file2.write(data)

file1.close()
file2.close()

file2= open(O, 'r')
data = file2.read()
print(data)

【讨论】:

  • 希望对您有所帮助
【解决方案2】:

file2 是文件对象而不是字符串,文件对象没有替换方法

试试

with open(I, 'r') as file1, open(O, 'w') as file2:
    for line in file1.readlines():
        line=line.replace(S,T)
        file2.write(line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-21
    • 2011-07-01
    • 2013-12-03
    • 2021-06-15
    • 2019-05-14
    • 1970-01-01
    • 2014-12-23
    • 2011-04-06
    相关资源
    最近更新 更多