简体   繁体   中英

Reading a file in Python for text

I am given

bus_stops0.txt    
01012,Victoria St,Hotel Grand Pacific
01013,Victoria St,St. Joseph's Ch
01019,Victoria St,Bras Basah Cplx

in a notepad and I have no idea how to open this file inside IDLE.

Also, I want to define

def read_data(filename):
    stops = [] 
    with open(filename,  'r') as f:
        for line in f:
            line = line[:-1]
            code, road_name, desc = line.split(',')
            stops.append(filename)
    return str(stops)

such that

read_data('bus_stops0.txt')

['01012,Victoria St,Hotel Grand Pacific', "01013,Victoria St,St. Joseph's Ch", '01019,Victoria St,Bras Basah Cplx']

Is my definition correct in the first place?

for desired output the definition is:

def read_data(filename):
   stops = []
   with open(filename,  'r') as f:
       for line in f:
           stops.append(line.replace('\n', ''))
   return str(stops)

Use the U flag for universal readlines mode.

def read_data(filename):
   stops = []
   with open(filename,  'rU') as f:
       for line in f:
           stops.append(line.strip())
   return stops

Alternately, you can simply return readlines if you want to preserve your newlines

def read_data(filename):
   with open(filename,  'rU') as f:
       return f.readlines()

If 'stops' are the third element for each file line and you want to use list comprehension:

def read_data(filename):
    with open(filename,  'r') as f:
        stops = [line.split(',')[-1] for line in f]
return str(stops)

If I understand you correctly, you need the output something like this

['01012,Victoria St,Hotel Grand Pacific', "01013,Victoria St,St. Joseph's Ch", '01019,Victoria St,Bras Basah Cplx']

If that would be the case then here is the code. Make sure file has read permission.

def read_data(filename):
    stops = []
    with open(filename,  'r') as fobj:
       for line in fobj:
           stops.append(line.strip())
    return stops

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