gpt4 book ai didi

python - 尝试在 python 中打开并读取文件,但它创建并打开一个空文件

转载 作者:太空宇宙 更新时间:2023-11-03 21:37:11 26 4
gpt4 key购买 nike

我正在尝试使用以下代码在 python 中打开多个 csv 文件:

file= open('file.csv', "r")

contents= file.read()
allLines = file.readlines()
print(contents)
print(allLines)

但是所有 python 打印都是“[]”

当我查看 python 项目的文件夹时 - 文件在那里,但现在是空的 - 出了什么问题?

最佳答案

关于为什么 python 打印空数组,我假设您只在打印 allLines 时遇到这种情况。当对打开的文件进行读取操作时,Python 会将读取光标保留在文件末尾。我相信如果您使用 seek(0) 您可以将读取光标返回到文件的开头。即:

file = open('file.csv', 'r')
contents = file.read()
file.seek(0)
allLines = file.readlines()
print(contents)
print(allLines)

关于python - 尝试在 python 中打开并读取文件,但它创建并打开一个空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com