2017-04-24 26 views
0

我正在使用linux8。我有一个包含文件的repo(带有subrepos),我有一个文件名列表(path/to/file/filename.pdf)。我想检查(使用Python),如果这些文件都存在,如果不存在,我想知道这一点。所以我尝试阅读列表,用for循环迭代列表条目,并使用os.path.isfile()。python:如何在列表(路径)上使用os.path.isfile()?

E.g.我有一个包含以下文件的回购: list.txt, test1.txt和 test2.txt。

list.txt包含文件名(这里是:'test1.txt''test2.txt')。

os.path.isfile('test1.txt') 

给人

True 

但这for循环...

import os 

with open('list.txt', 'r') as f: 
    pathlist=f.readlines() 
for path in pathlist: 
    print(os.path.isfile(path)) 

...给:

False 
False 

虽然

type(path) 

<type 'str'> 

这感觉就像是巨蟒区分两种类型的字符串。有谁知道,从哪里来?

+0

的种类。 Python最后从没有字符串的字符串中用新行区分字符串。尝试从文件读取的行上调用['strip()'](https://docs.python.org/2/library/stdtypes.html#str.strip)。 – khelwood

+0

试试'print(repr(path))'''readlines'不去掉换行符,你需要自己去做。 – tdelaney

+0

'pathlist = map(str.strip,pathlist)'将完成这项工作 –

回答

0

两个可能的问题。

首先,您可能没有在您认为自己的目录中运行。

其次,readlines()将返回带有换行符和可能回车符的行。在将它们作为路径进行测试之前,您需要删除它们。您可以使用rstrip()从字符串中删除尾随空格。

for path in pathlist: 
    print(os.path.isfile(path.rstrip())) 
+0

工作完全正常。我想到了,打印列表“路径列表”时。但不知道,如何表达这个问题。非常感谢! – tharndt

0

可以遍历文件的行,并检查每一条路径如下存在:

import os 

with open('list.txt', 'r') as fd: 
    for line in fd: 
     path = line.strip() # drop \n 
     if os.path.isfile(path): 
      print(path) 
+0

工作得很好。谢谢! – tharndt

1

考虑

os.path.isfile("/tmp") # True 

os.path.isfile("/tmp\n") # False 

尝试,而不是:

with open("/pathlist", "r") as f: 
    for path in map(str.strip, f.readlines()): 
     print(os.path.isfile(path)) 
+0

这甚至更短。尼斯。工作正常!谢谢! – tharndt

相关问题