简体   繁体   中英

Using Python to read a text file

I am currently trying to make a program that can read a text file that is updated from a program. I am using this program to determine if a computer should be shutdown in the case of a power outage by communicating with a UPS. The program that is outputting data to the text file is called Batterymon. I know that other programs exist for battery backups but this is the one I decided to work with. So far I am able to read the file and get it to print using python but it prints all of the data. I only really need a tiny amount of data for what I am doing. This is my code so far.

import csv
with open('Test.txt', 'r') as f:
     reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
     for line in reader:
             print(f.readline())

Note: I imported csv because after some searching I found that was relevant to what I was doing.

I am new to python as I have only been using it a couple of days now. I tried putting a value in the readline() command but it started from the beginning of the line (which has unneeded information). I want to be able to read what is in the middle of the line. I also would really just like to try to print the line by itself or print the most recently added line.

This is one of the lines printed from my current code, it prints about 1000 of these indicating the time and battery percentage.

2018-08-15, 09:54:51, OK, 60%, 2.88, 6231, -19380, , 15.200, -19380, 60.3%, , , , , , , , , , , , 

I am trying to only print the percent and the OK status. Is python the best choice to use for something like this? If I can get this to work then I will add commands to shutdown the computer. I suppose this is kind of a long question, but in the least I would like to know if there is a way to just print part of the line that is being printed.

Below code should print only that values which you need

import csv
with open('Test.txt', 'r') as f:
   reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
   for line in reader:
       print(f.readline().split(', ')[3:4])

You can split each line by comma, assuming every line is the same format:

items = f.readline().split(', ')
okay_status = items[2]
percentage = items[10] # or items[3]?

#... use variables here...

You can use Pandas (a Python library for data processing):

import pandas as pd

data = pd.read_csv('Test.txt')

ok = data.iloc[:, 2]

percentage = data.iloc[:, 3]

If your CSV file has column names (eg OK and percentage ), you can instead use:

ok = data['OK']
percentage = data['percentage']

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