gpt4 book ai didi

python - 如何创建循环来替换可变数量的行

转载 作者:行者123 更新时间:2023-12-01 02:30:16 24 4
gpt4 key购买 nike

所以我正在尝试替换 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)

最佳答案

line = newline

只需将名称重新绑定(bind)到换行符的值。它不会修改 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)

关于python - 如何创建循环来替换可变数量的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46908897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com