我得到了
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']
首先我的定义是否正确?
答案 0 :(得分:1)
对于所需的输出,定义为:
def read_data(filename):
stops = []
with open(filename, 'r') as f:
for line in f:
stops.append(line.replace('\n', ''))
return str(stops)
答案 1 :(得分:1)
将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()
答案 2 :(得分:1)
如果'stops'是每个文件行的第三个元素,并且您想使用列表推导:
def read_data(filename):
with open(filename, 'r') as f:
stops = [line.split(',')[-1] for line in f]
return str(stops)
答案 3 :(得分:0)
如果我理解正确,你需要像这样的输出
['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