简体   繁体   English

从文本文件Python中的特定行删除空间

[英]Remove Space from Particular line In Textfile Python

I have textfiles that have the date stored on line 7 of each file, formatted as such: 我有一些文本文件,其日期存储在每个文件的第7行,格式如下:

    Date:  1233PM 14 MAY 00

I would like to search through each file and get the new line 7 to be formatted as such: 我想搜索每个文件,然后将新行7格式化为:

    Date:  1233PM 14 MAY 2000

So, basically, I just need to stick a '20' in front of the last two digits in line seven. 因此,基本上,我只需要在第7行的最后两位数字前加上“ 20”即可。

Probably not the most difficult problem, but I have been having difficulty as textfile.readlines() reads everything into the first (textfile[0]) position. 可能不是最困难的问题,但是当textfile.readlines()将所有内容读取到第一(textfile [0])位置时,我一直遇到困难。

You can read all the file, change the specified line then save it again: 您可以读取所有文件,更改指定的行,然后再次保存:

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()

Try this: 尝试这个:

# 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

Maybe this: 也许这样:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM