Python file.read() 返回一个空字符串

问题描述 投票:0回答:1

我需要打开一个包含单词列表的文件。在python中,应该比较简单,但是file.read()函数总是不返回数据

一开始我尝试过

if os.path.exists("words.txt"):
    print("File exists.")
with open("words.txt", "r") as file:
    print(file.read().splitlines())

这不会返回任何数据。我认为这可能是因为 splitlines 功能,所以我尝试了这个

if os.path.exists("words.txt"):
    print("File exists.")
with open("words.txt", "r") as file:
    print(file.read())

与以前相同,但没有分割线功能。这也不会返回任何数据。

两者都返回“文件存在。”

python file-io
1个回答
0
投票

你可以试试这个:

file = open("words.txt")
            read_file = file.readlines()
            file.close()
            print(read_file)
© www.soinside.com 2019 - 2024. All rights reserved.