作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在编辑文件内容时,我一直使用以下方法:
.read()
方法将文件内容转换为字符串并分配给另一个变量例如:
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/
我是一名优秀的程序员,十分优秀!