gpt4 book ai didi

Python 错误 : read the contents in a file into variable

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:21 25 4
gpt4 key购买 nike

我在 shell 中成功地做到了这一点

readonly FILE="/home/xxxx/file.txt"
text=$(cat ${FILE})

在 python 中尝试相同的方法

text = open('file.txt').read()
print text

我正在尝试这个,但出现错误:

Traceback (most recent call last):
File "C:\Python27\lib\runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\lib\py_compile.py", line 170, in <module>
sys.exit(main())
File "C:\Python27\lib\py_compile.py", line 162, in main
compile(filename, doraise=True)
File "C:\Python27\lib\py_compile.py", line 106, in compile
with open(file, 'U') as f:
IOError: [Errno 22] invalid mode ('U') or filename: ''

谢谢!

最佳答案

回溯中的这一行:IOError: [Errno 22] invalid mode ('U') or filename: '' 告诉我你正在为上下文管理器提供一个空字符串作为文件名.确保定义了变量 file

关于Python 错误 : read the contents in a file into variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45579992/

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