我有一个长文本文件,总是以32个字符的MD5哈希开头,如下所示:
f4f494da100a3577420a7ff7c32abb5707:55:40 PM | username: text
我的目标是去除此文件第一行的前32个字符,然后覆盖该行。我的代码(下面)成功地抓取了行并剥离了字符,但删除了文件中的其他所有内容。
with open(x, 'r') as fin:
lines = fin.readlines()
lines = lines[0]
lines = lines[32:]
with open(x, 'w') as fout:
for line in lines:
fout.write(line)
我知道我可以使用lines[0]
修改第一行,但我不确定如何删除那些字符(也许re
?)
答案 0 :(得分:3)
您只需手动阅读前32个字符,然后拨打readlines
阅读其余字符:
with open(x, 'r') as fin:
header = fin.read(32)
lines = fin.readlines()
with open(x, 'w') as fout:
fout.writelines(lines)
答案 1 :(得分:2)
使用lines[0]
很好 - 唯一的问题是您要覆盖lines
变量,从而丢失其他行:
with open(x, 'r') as fin:
lines = fin.readlines()
lines[0] = lines[0][32:] # Strip just the first line
with open(x, 'w') as fout:
for line in lines:
fout.write(line)