将文本文件中的行读入variab

2024-04-29 10:48:09 发布

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

我的桌面上有一个文本文件lines.txt

lines stuff stuff
lines lines
boats boats lines

我只想把它读入一个变量,但每次打印它时,都会得到一个空列表。这是我的密码:

inF = 'C:/Users/me/Desktop/text.txt' def repeatWords(inF): import string infile = open(inF, 'r') text = infile.readlines() infile.close() print(text) repeatWords(inF)

当我print(text)时,我得到的只是一个空列表。我做错什么了?你知道吗


Tags: texttxt密码列表usersinfile桌面上inf
3条回答

我想你调用了text函数。注意,函数中的变量有一个局部作用域,因此需要在函数中调用text!你知道吗

file_object = open("myfile", 'r')
for line in file_object:
    print(line)
file_object.close()

你的代码有很多问题。我不知道您在哪里调用print(text),但它需要在分配给之后。以下是更正的版本:

def repeat_words(in_f, out_f):
    with open(in_f, 'r') as infile:
        text = infile.readlines()
        print(text)

相关问题 更多 >