[英]Open multiple files from a file
I need to open a file that have multiple absolute file directories. 我需要打开一个具有多个绝对文件目录的文件。
EX: 例如:
Layer 1 = C:\\User\\Files\\Menu\\Menu.snt 第1层= C:\\ User \\ Files \\ Menu \\ Menu.snt
Layer 2 = C:\\User\\Files\\N0 - Vertical.snt 第2层= C:\\ User \\ Files \\ N0-Vertical.snt
The problem is that when I try to open C:\\User\\Files\\Menu\\Menu.snt python doesn't like \\U or \\N 问题是当我尝试打开C:\\ User \\ Files \\ Menu \\ Menu.snt时, python不喜欢\\ U或\\ N
I could open using r"C:\\User\\Files\\Menu\\Menu.snt"
but I can't automate this process. 我可以使用r"C:\\User\\Files\\Menu\\Menu.snt"
但无法自动执行此过程。
file = open(config.txt, "r").read()
list = []
for line in file.split("\n"):
list.append(open(line.split("=",1)[1]).read())
It prints out: 它输出:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 33-34: malformed \N character escape
The backslash character \\
is used as an escape character by the Python interpreter in order to provide special characters. Python解释程序将反斜杠字符\\
用作转义字符,以提供特殊字符。
For example, \\n
is a "New Line" character, like you would get from pressing the Return key on your keyboard. 例如, \\n
是“换行”字符,就像您按键盘上的Return键一样。
So if you are trying to read something like newFolder1\\newFolder2
, the interpreter reads it as: 因此,如果您尝试读取诸如newFolder1\\newFolder2
,则解释器将其读取为:
newFolder1
ewFolder2
where the New Line character has been inserted between the two lines of text. 在两行文本之间插入了换行符的位置。
You already mentioned one workaround: using raw strings like r'my\\folder\\structure'
and I'm a little curious why this can't be automated. 您已经提到了一种解决方法:使用原始字符串(例如r'my\\folder\\structure'
,我有点好奇为什么这不能自动化。
If you can automate it, you could try replacing all instances of a single backslash ( \\
) with a double backslash ( \\\\
) in your file paths and that should work. 如果可以自动执行,则可以尝试在文件路径中用双反斜杠( \\\\
)替换单个反斜杠( \\
)的所有实例,这应该可以工作。
Alternatively, you can try looking in the os
module and dynamically building your paths using os.path.join()
, along with the os.sep
operator. 另外,您可以尝试查看os
模块,并使用os.path.join()
和os.sep
运算符动态构建路径。
One final point: You can save yourself some effort by replacing: 最后一点:您可以通过替换以下内容来节省一些精力:
list.append(open(line.split("=",1)[1]).read())
by 通过
list = open(line.split("=",1)[1]).readlines()
here is my solution: 这是我的解决方案:
file = open("config.txt", "r").readlines()
list = [open(x.split("=")[1].strip(), 'r').read() for x in file]
readlines creates a list that contains all lines in file, there is no need to split the whole string. readlines创建一个包含文件中所有行的列表,无需拆分整个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.