【发布时间】:2020-07-12 17:19:32
【问题描述】:
我有以下代码:
#!/usr/bin/python
import os
from sys import exit as EXIT
File = os.path.realpath(__file__)
dir = os.path.dirname(File)
os.chdir(dir)
path_file = os.path.join(dir,"path.txt")
filo = open(path_file)
lines = filo.readlines()
if len(lines) == 1:
path = lines[0]
else:
raw_input("Too many lines... ")
EXIT()
FILE = open(path)
当我运行它时,我得到了错误:
Traceback (most recent call last):
File "py/Zebra/zebra.py", line 20, in <module>
FILE = open(path)
IOError: [Errno 2] No such file or directory: 'C:\\Users\\user\\file.txt'
如果路径是硬编码的,那么我可以做类似的事情 路径 = r"C:\path\to\file"
但由于该变量是由其他方法定义的,我现在不确定要解决这个问题:(
【问题讨论】:
-
我认为您的问题与原始字符串无关 - 反斜杠的转义看起来是正确的。
-
该文件是否确实存在于该路径中?
-
从第一行开始,我假设您正在运行 Linux。
'C:\\Users...'不应该存在于 Linux 系统上,因此无法找到它。如果是这样,你能不能尝试一个有效的路径,看看错误是否继续?
标签: python python-2.7 rawstring