[英]Is there a way to remove entire parts of lines from a text file in Python, then remove certain parts of the rest?
I have a text file that looks like this:我有一个看起来像这样的文本文件:
Close
Datetime
2021-07-02 09:30:00-04:00 93.080002
2021-07-02 09:30:00-04:00 93.080002
2021-07-02 09:31:00-04:00 93.026001
2021-07-02 09:32:00-04:00 92.405403
2021-07-02 09:33:00-04:00 92.370003
I would like it to look like this:我希望它看起来像这样:
93.080002
93.080002
93.026001
92.405403
92.370003
Is there a way to do this in Python by erasing the first 2 lines and then erasing only the times in the rest?有没有办法在 Python 中通过擦除前 2 行然后只擦除其余的时间来做到这一点? Thanks in advance.提前致谢。
Given:鉴于:
$cat ur_file
Close
Datetime
2021-07-02 09:30:00-04:00 93.080002
2021-07-02 09:30:00-04:00 93.080002
2021-07-02 09:31:00-04:00 93.026001
2021-07-02 09:32:00-04:00 92.405403
2021-07-02 09:33:00-04:00 92.370003
You can do:你可以做:
with open(ur_file) as f_in:
data=[line.strip().split()[-1] for i,line in enumerate(f_in) if i>1]
Result:结果:
>>> data
['93.080002', '93.080002', '93.026001', '92.405403', '92.370003']
or:要么:
>>> print('\n'.join(data))
93.080002
93.080002
93.026001
92.405403
92.370003
If you want a filter that writes the output to a file:如果您想要一个将输出写入文件的过滤器:
with open(ur_file) as f_in, open(out_file, 'w') as f_out:
for i, line in enumerate(f_in):
if i>1:
f_out.write(f'{line.split()[-1]}\n')
Which results in an output file as desired.这会产生所需的输出文件。
using `test.txt as input file:使用 `test.txt 作为输入文件:
Close
Datetime
2021-07-02 09:30:00-04:00 93.080002
2021-07-02 09:30:00-04:00 93.080002
2021-07-02 09:31:00-04:00 93.026001
2021-07-02 09:32:00-04:00 92.405403
2021-07-02 09:33:00-04:00 92.370003
using code:使用代码:
with open('test.txt' , 'r') as handle: #open test.txt file as handle, read mode and text mode (default)
pippo = handle.readlines() #reads the handle file all at once into lines
with open('res.txt' , 'w+') as whandle: #open res.txt file to write to it, write mode and text mode (default)
for i in range(0,len(pippo)): # loops over the file lines from 0 to lenght of readlines alias number of lines
if i > 1: # starts at second line on (lines start at zero su skips line 0 and line 1
print(pippo[i].split()[2]) # print line i splitted by whitespace third element: the number you are looking for
whandle.write(pippo[i].split()[2]+'\n') #writes the above lines adding \n line terminator to res.txt file
writes result as res.txt
file:将结果写入res.txt
文件:
93.080002
93.080002
93.026001
92.405403
92.370003
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.