当前位置: 代码迷 >> python >> 在Python中读取文件以获取文本
  详细解决方案

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

热度:27   发布时间:2023-07-14 08:59:06.0

我得到了

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