一道python的题目,求大神指导

2025-06-26 18:57:42
推荐回答(2个)
回答1:

如果是这要输出:['this is the 1 line','this is the 2 line','this is the 3 line','this is the 4 line','this is the 5 line','this is the 6 line','this is the 7 line']
这种格式,只把把文件内容读到数组,然后直接print数组就行,代码如下:

def readLines(fileName): 
    inputFile = open(fileName, 'r') 
    if inputFile == None: 
        print("ERROR: unable to read file", fileName) 
    else: 
        line = inputFile.readline()
        arr = []
        while len(line) > 0:
            arr.append(line.strip())
            line = inputFile.readline()
        print(arr)

readLines('fo.txt')

回答2:

def readLines(fileName): 
    inputFile = open(fileName, 'r') 
    if inputFile == None: 
        print("ERROR: unable to read file", fileName) 
    else: 
        print ([i.strip() for i in inputFile.readlines()])
readLines('fo.txt')


>>> 
['this is the 1 line', 'this is the 2 line', 'this is the 3 line', 'this is the 4 line', 'this is the 5 line', 'this is the 6 line', 'this is the 7 line']
>>>