如何创建一个循环来替换可变数量的行

时间:2017-10-24 11:05:10

标签: python loops replace

所以我试图替换x号。带有该行新版本的文本文件中的行。新行与旧行相同但没有第一个字符'#'。我不能删除第一个字符,当然,字符串是不可变的。 我已在下面创建了该脚本,但不会进行更改。当我打印有问题的部分时,它没有变化。我也尝试过使用string.replace(),但也没有用过。 没有错误出现,所以我不知道自己哪里出错了。

import os
import subprocess 

x = input('How many unique conformers were identified? ') 
with open('file.txt', 'r') as f: 
  f_contents = f.readlines() 
  for line in (f_contents[18:(18 + x)]):
    newline = str(line[1:(len(line))])
    if line[0] == "#":
      line = newline
print f_contents[18:(18 + x)] 

  with open('x.txt', 'w') as f: 
    f.writelines(f_contents)  

2 个答案:

答案 0 :(得分:1)

line = newline

只需将名称 line重新绑定到newline的值即可。它不会修改f_contents的值,因为该值是不可变的。

您可以尝试此操作来更新f_contents列表:

offset = 18
x = input('How many unique conformers were identified? ')

with open('file.txt', 'r') as f: 
  f_contents = f.readlines()
  for i in range(offset, offset + x):
    if f_contents[i].startswith('#'):
        f_contents[i] = f_contents[i][1:]

print f_contents[offset:offset + x]

使用列表推导的切片分配也可以起作用:

with open('file.txt', 'r') as f:
  f_contents = f.readlines()
  f_contents[offset:offset+x] = [line[1:] if line.startswith('#') else line
                                    for line in f_contents[offset:offset+x]]

如果您的目标是将更新的内容写回文件,那么更好的方法是迭代文件中的行,更新所需行范围内的行,然后写出新文件。

offset = 18
x = input('How many unique conformers were identified? ')

with open('file.txt', 'r') as infile, open('outfile.txt', 'w') as outfile:
    for i, line in enumerate(infile):
        if offset <= i < offset+x and line.startswith('#'):
            line = line[1:]
        outfile.write(line)

答案 1 :(得分:1)

让我介绍标准库模块fileinput

import fileinput

x = input('How many unique conformers were identified? ')
# Python3 input() returns an unevaluated string
x = int(x) 

# fileinput objects can be used as context managers
# the inplace=True argument directs to edit the file in place...

with fileinput.input('file.txt', inplace=True) as f:

  for line in f:
      # decrement the line number to match the list indexing of OP
      ln = f.lineno() - 1
      # use "<=" and "<" to match slice addressing
      if 18 <= ln < (18+x):
          # if first character is "#" remove it
          if line[0]=='#': line = line[1:]
      print(line, end='')

让我引用上面链接的网站:

  

虽然脚本使用print(),但是没有输出,因为fileinput会将标准输出重定向到被覆盖的文件。

PS忘了提 - 在进一步处理之前会生成备份文件......