简体   繁体   中英

Retrieve a number from a text file in Python

I'm new to Python.
I have a program that saves temperature and humidity values to a text file. I can't figure out how to retrieve any of the saved values (which I will then use to compare with current temperature and humidity readings).

The data is saved in this format.

22:48
23:49
24:52

I would like to retrieve the first row and turn them both into two variables (temp and humidity). This is as far as I've got but it just returns the value 2. I'd really appreciate any advice.

mylines = []                              
with open ('log.txt','r') as myfile: 
     for myline in myfile:                
         mylines.append(myline)           
 
 mylines[0].split(':')
 
print(mylines[0][1])

You need to assign the result of split as it doesn't mutate. You can do this to the whole array like so:

with open ("log.txt", "r") as myfile:
    for myline in myfile:
        mylines.append(myline.split(":"))

print(mylines[0][1]) # This should now print '48'

Or for your specific example:

mylines[0] = mylines[0].split(":")

To go a bit further and make temp and humidity arrays is fairly simple too:

temp = []
humidity = []
with open ("log.txt", "r") as myfile:
    for myline in myfile:
        t, h = list(map(int, myline.split(":")))
        temp.append(t)
        humidity.append(h)

If you only want the values from the first line in the file and presumably want them as integers then:

with open('log.txt') as th:
    temp, humidity = map(int, next(th).split(':'))
    print(temp, humidity)

Output:

22 48

As noted earlier, Jack's solution will work fine. Might be worth taking advantage of some libraries and trying to get yourself familiar with dictionaries - they're great [and then go explore dataframes afterwards].

import csv

text_file = r"C:\Path\To\Text\File.txt"

header = ["temp", "humidity"]
with open(text_file, mode="r") as f:  # mode="r" for readonly
    reader = csv.reader(f, delimiter=":")  # Telling the csv module we want to use ":" as our delimiter  
    dict_from_file = [dict(zip(header, list(row))) for row in reader]

So, we've declared the header in a separate list. You could grab that off the first row in the text file if needed, but would need to adapt the above of course.

Then dict(zip()) is combining the list "header" and the list "row" for each row in the file. zip() nominally outputs tuple pairs, which we've then subsequently converted to dictionary pairs using dict()

Which will give you a (list) output of:

[
{'temp': '22', 'humidity': '48'},
{'temp': '23', 'humidity': '49'},
{'temp': '24', 'humidity': '52'},
]

Hopefully of some use to you.

edit: There is actually a tidier way using the csv library - reusing the text_file and header declared above...

dict_from_file = []
with open(text_file, mode="r") as f:
    reader = csv.DictReader(f, header, delimiter=":")
    for row in reader:
        dict_from_file.append(row)

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