简体   繁体   中英

Extract a number from a txt file

Apologies to all, I am rewriting the question to be clearer than before. I have text files that are renamed like this: 1.txt, 2.txt, ... etc. (for a total of 195 files). These text files contain two blocks made like this:

Assuming your data is stored in text.txt file. I only take the last 5 elements of a line.

with open('text.txt') as f:
    file_list = f.readlines()
new_list = [] 
for sentence in file_list:
    new_list.append(sentence.replace('\n', ''))
list_number = []
for element in new_list:
    list_number.append(element.split()[:-6:-1])

Output:

[['-0.34011', '-0.34412', '-0.34682', '-0.35095', '-0.35790'],
 ['-0.28924', '-0.30201', '-0.31434', '-0.32013', '-0.33775'],
 ['-0.27505', '-0.27672', '-0.28216', '-0.28518', '-0.28686'],
 ['0.02156', '0.00150', '-0.02072', '-0.10541', '-0.12386'],
 ['0.05155', '0.04675', '0.04449', '0.03997', '0.03129'],
 ['0.08236', '0.08193', '0.07459', '0.06358', '0.06062']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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