繁体   English   中英

在Python中读取文件以获取文本

[英]Reading a file in Python for text

我得到了

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

在记事本中,我不知道如何在IDLE中打开此文件。

另外,我想定义

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)

这样

read_data('bus_stops0.txt')

['01012,Victoria St,Hotel Grand Pacific',“ 01013,Victoria St,St。Joseph's Ch”,'01019,Victoria St,Bras Basah Cplx']

首先我的定义正确吗?

对于所需的输出,定义为:

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

U标志用于通用阅读线模式。

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

或者,如果您想保留换行符,则可以简单地返回readlines

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

如果“ stops”是每个文件行的第三个元素,并且您想使用列表推导:

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

如果我理解正确,则需要类似以下的输出

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

如果真是这样,那么这里是代码。 确保文件具有读取权限。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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