【问题标题】:Python Write Line with two operationsPython Write Line 有两个操作
【发布时间】:2014-08-13 09:07:28
【问题描述】:

我有这个工作代码:

S095    = 'S095' 
E095    = 'E095'

DocLan = 'c:\DocLan.asc'
tempDocLan = open( DocLan, 'r+' )

for line in fileinput.input( DocLan ):
    if fileinput.lineno() > 1:
        LanNr = find_nth(line, "S095", 1), " - ",
                line[find_nth(line, "S095", 1) + 5: find_nth(line, "S095", 1) + 14]
        if LanNr > 10:
            tempDocLan.write(line.replace(S095, E095))
        else:
            ""
    else:
        tempDocLan.write(line)

tempDocLan.close()

我已尝试更改代码以添加第二个写入操作:

for line in fileinput.input(DocLan):
    if fileinput.lineno() > 1 :
        LanNr = find_nth(line, "S095", 1), " - ",
                line[find_nth(line, "S095", 1) + 5: find_nth(line, "S095", 1) + 14]

        if LanNr > 10:
            tempDocLan.write(line.replace(S095, E095))

            # error here
            tempDocLan.write(line[0:50])
        else:
            ""
    else:
        tempDocLan.write(line)

tempDocLan.close()

在第一次写入时,我将文本 S095 替换为 E095 在第二次写入中,我想剪切文本(已经 E095),但它不起作用。


我正在使用 Python 2.7。

我举个例子。 我有一个包含此内容的文件。

删除,S095/20140001,

删除,S095/20140002,

删除,S095/20140003,

删除,S095/20140004,

删除,S095/20140005,

删除,S095/20140006,

我想创建这个文件。

E095/20140001,

E095/20140002,

E095/20140003,

E095/20140004,

E095/20140005,

E095/20140006,

感谢您的帮助。

罗梅乌克卢格

【问题讨论】:

  • 错误是什么..?

标签: python text alter


【解决方案1】:

这就是你想做的,很简单:

  • 用空格分隔行。
  • 将 S 替换为 E。
  • 写。

它已经完成了。

with open("input_file.txt") as input_file, open("output.txt", "w") as output:
    for line in input_file:
        _, tag = line.split()
        tag.replace("S", "E")

        output.write(tag)

【讨论】:

    猜你喜欢
    • 2012-06-04
    • 2014-10-11
    • 2020-10-19
    • 2017-04-14
    • 1970-01-01
    • 2011-05-20
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多