【问题标题】:Replace from second line onwards [closed]从第二行开始替换[关闭]
【发布时间】:2021-02-24 10:26:20
【问题描述】:

我有一个文本文件,我需要从第二行开始替换它的数据并将其写入包含所有输入文件行的 fout 文件。

我试过代码

fout=open('f2','w')
fin=open('f1','r')
for line in f1:
   
   line=line.replace("()","(n)",1)
   fout.write(line)

但我无法达到预期的效果。

【问题讨论】:

  • NameError f1'somebigstringreadfromf1'[2:1] 上的 SliceError 是空的,lines 上的 NameError。你又是什么问题?你真的运行过这个“代码”吗?在解决所有问题后,通过editing 添加您的堆栈跟踪,您可以自己调试和研究它们

标签: python


【解决方案1】:

您的代码中几乎没有错误,首先您指的是f1 写作f1 而不是fin。第二件事,您需要读取从2 到文件末尾的行。

您可以通过读取第一行来实现这一点(用它做你想做的),然后遍历文件的其余部分。

我无法对您的文件执行此操作,但类似这样的方法可以工作:

fout=open('f2','w')
fin=open('f1','r')
first_line = fin.readline()
fout.write(first_line) #if you want to print that out
for line in fin: #iterate over the rest of the file line by line
    #dothings: no need to fin.read()
    line = line.replace("()","(n)",1)
    fout.write(line)

【讨论】:

  • 输入错误。我纠正了它。我想替换第二行的文本。我该怎么做
  • first_line = f.readline() 这里ffin 对吗??
  • @NEHACHOUDHARY 是的!你是对的
【解决方案2】:

我设法用这种方法做到了,我尝试使用 seek() 但似乎没有像我预期的那样工作:

# read content
with open('f1', 'r') as fh:
  f1 = fh.read()

with open('f2', 'r') as fh:
  f2 = fh.read()

# convert to list
f1 = f1.split('\n')
f2 = f2.split('\n')

# modify lists
f1 = [f1[0]]
for line in f2:
  f1.append(line)

f1 = '\n'.join(f1)

# finally write to file
with open('output', 'w') as fh:
  fh.write(f1)

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多