简体   繁体   中英

How to read the numeric number in a specific location in a txt file in python?

I have an output txt file and I only want the number 13.0 in line 151

13.0 = ebeam1 ! beam 1 total energy in GeV

and 74.761227 line 479

# Integrated weight (pb) : 74.761227

I wonder how to read these numbers and write them as a line in another file?

You want to use the linecache module.

import linecache
line = linecache.get('path/to/file', 479)

Then write it to another file.

with open('other/file.txt', 'w') as f:
    f.write(line)

Assuming you want to extract just the number portion of the line:

import re
In [4]: re.search(r'(\d+.*\d*$)', line).group()
Out[4]: '74.761227'

Cory Madden's answer will work, but if you didn't know what number the line you're looking for is on you could do something like:

import re

regex = re.compile(r"# Integrated weight \(pb\) : (?P<number>-?\d+\.?\d*)")

with open(file_path, "r") as lines:
    for line in lines:
        match = re.match(regex, line)
        if match:
            number = float(match.group("number"))
            return number
import linecache
import re

ln = linecache.getline('so_qn_test_file.txt', 479)
nums = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", ln)
# print(nums)
with open('op_file.txt','w') as f:
    f.write(','.join(nums))

This will work. I have already tested it. For explanation for Regex , this should help.

Thank God for your question, you will basically use a for loop to loop through the lines in the file and add each line to a list. So that at anytime you can call the list with the line number you want and that particular line will be delivered to you. You then save it in a variable and then apply regular expression(regex) on it, to get only the floating numbers.

example txt file:

151 Jesus 13.0
152 John
153 Peter 74.745392

then in your python file

import re

file_line_arr = []
with open('example.txt', 'r') as file:
    for line in file:
        file_line_arr.append(line)
line_1 = file_line_arr[151-1]
line_3 = file_line_arr[153-1]

first_number = re.findall('\d+.?\d+', line_1 )
second_number = re.findall('\d+.?\d+', line_3)

first_number_wq = re.sub("'", "", str(first_number))
first_number_wb = re.sub('(\[|\])', '', first_number_wq)

second_number_wq = re.sub("'", "", str(second_number))
second_number_wb = re.sub('(\[|\])', '', second_number_wq)

with open('new_file.txt', 'w') as new_file:
    new_file.write(first_number_wb + '\n' + second_number_wb)

Here is a book on python that you will like very much - ( dive into python3 ) search for it

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