-3

我有以下代码:

#!/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'

如果路径是硬编码的,那么我可以执行类似 path = r"C:\path\to\file" 的操作

但由于该变量是由其他方法定义的,我现在不确定要解决这个问题:(

4

1 回答 1

1

背后的想法r' '是编写原始字符串文字,因为它改变了 python 转义字符的方式。如果它恰好是来自变量的值,如上所述,则不需要使用r' ',因为您没有明确编写字符串文字。

无论哪种方式,我认为这会做:

path = r'%s' % pathToFile

编辑: 另外,正如对该问题的评论,您应该确保路径存在。

于 2020-04-01T02:43:03.097 回答