在Python中移除文本文件中特定行的空格

0 投票
3 回答
807 浏览
提问于 2025-04-17 18:05

我有一些文本文件,每个文件的第七行存储着日期,格式是这样的:

    Date:  1233PM 14 MAY 00

我想要查找每个文件,并把第七行的日期格式改成这样:

    Date:  1233PM 14 MAY 2000

简单来说,我只需要在第七行最后两位数字前面加个'20'。

这可能不是最难的问题,但我遇到了一些困难,因为使用textfile.readlines()会把所有内容都读到第一个位置(textfile[0])。

3 个回答

0

也许可以这样做:

with open(filename, 'r') as f:
    lines = f.readlines()

with open(filename, 'w') as f:
    for idx, line in lines:
        if idx == 7: # or 6
            vals = line.split()
            if len(vals[-1]) == 2:
                vals[-1] = '20'+vals[-1]
            line = ' '.join(vals)
        f.write(line)
0

试试这个:

# open file
f = open("file.txt" , 'rU+b')
lines = f.readlines()

# modify line 7
lines[6] = lines[6][:-2] + "20" + lines[6][-2:]

# return file pointer to the top so we can rewrite the file
f.seek(0)
f.truncate()

# write the file with new content
f.write(''.join(lines))
f.close
0

你可以把整个文件都读出来,修改指定的那一行,然后再保存回来:

arc = open('file_name.txt').readlines()[0].split('\r')

#Do what you want with the 7th line i.e. arc[6]

new_arc = open('file_name.txt','w')
for line in arc:
    new_arc.write(line)
    new_arc.write('\n')

new_arc.close()

撰写回答