Skip to main content
 首页 » 编程设计

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

2024年10月01日9oomusou

我在 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。