readlines()在Python中是如何工作的?

2024-10-03 15:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白readlines()在Python中是如何工作的,在本例中是Python 2。让我解释一下,我在一个文件中有以下函数,我通过“导入”在其他文件中使用,比如一个包

def openFileForReading(filePath):
if not fileExists(filePath):
    print 'The file, ' + filePath + 'does not exist - cannot read it.'
    return ''
else: 
    fileHandle = open(filePath, 'r')
return fileHandle

在我的新计划中,我会这样做:

openFileRead = openFileForReading("Orden.txt")
lineList = openFileRead.readlines()
print lineList

它给我的输出是:

[]

但如果我直接在文件中执行此操作,而不使用我的package函数,则它可以工作:

fileHandle = open("Orden.txt", 'r')
lineList = fileHandle.readlines()
print lineList

为什么如果我直接这样做,它会工作,但如果我通过一个包的函数这样做,它不会工作

注意:“Orden.txt”文件不是空的,它有两行:

Orden.txt
Line number 1
Line number 2

Tags: 文件函数txtreturnlinenotopenprint