gpt4 book ai didi

python - 如何将文件内容修改为字符串,同时有权访问影响字符串中的行的方法?

转载 作者:行者123 更新时间:2023-12-01 05:42:09 24 4
gpt4 key购买 nike

在编辑文件内容时,我一直使用以下方法:

  1. 以读取模式打开文件
  2. 使用 .read() 方法将文件内容转换为字符串并分配给另一个变量
  3. 关闭文件
  4. 对字符串进行操作
  5. 以写入模式打开原始文件
  6. 将字符串写入文件
  7. 关闭文件

例如:

fo = open('file.html', r)
fo_as_string = fo.read()
fo.close()
# # #
# do stuff to fo_as_string here
# # #
fo = open('file.html', w)
fo.write(fo_as_string)
fo.close()

我现在发现自己处于这样的情况,但是我需要删除行开头的任何空格,并且我认为因为我已将文件对象转换为字符串,所以无法定位目标这个空白,在“行”级别,使用 lstrip 和 rstrip 等字符串方法。

所以我想我正在寻求关于如何保留将文件内容作为字符串进行操作的灵 active 的逻辑建议,而且还能够在需要时将字符串中的行作为特定行操作的目标,如上面的示例所示。

最佳答案

使用for循环,文件对象上的for循环一次返回一行。

#use `with` statement for handling files, it automatically closes the file for you.
with open('file.html') as fo, open('file1.html', 'w') as fo1:
for line in fo: #reads one line at a time, memory efficient
#do something with line, line.strip()
fo1.write(line + '\n') #write line to to fo1

如果您尝试修改同一文件,请使用fileinput模块:

import fileinput
for line in fileinput.input('file.html', inplace = True):
#do something with line
print line #writes the line back to 'file.html'

您还可以从 file.read() 获取单独的行,并使用以下方法分割它:

fo_as_string = fo.read()
lines = fo_as_string.splitlines()

但是 file.read() 将整个文件加载到内存中,因此内存效率并不高。

其他替代方案是 f.readlines()list(f),两者都返回文件对象中所有行的列表。

关于python - 如何将文件内容修改为字符串,同时有权访问影响字符串中的行的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17258406/

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