【问题标题】:Make Python string a raw string使 Python 字符串成为原始字符串
【发布时间】: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


【解决方案1】:

r' '背后的想法是写raw string literals,因为它改变了python转义字符的方式。如果它碰巧是来自变量的值,如上所述,则不需要使用r' ',因为您没有显式编写字符串文字。

不管怎样,我认为这样可以:

path = r'%s' % pathToFile

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多