我有一个文件(' sample.txt'),它包含我系统中目录的所有路径。您可以在下面看到该文件的几行
/media/arjith007/Education/$RECYCLE.BIN
/media/arjith007/Education/.Trash-1000
/media/arjith007/Education/output.txt
我的任务是读取文件中的所有行(' sample.txt'),我应该确定给定的路径是文件还是目录。我使用的代码是:
import os
f = open('sample.txt','r')
for line in f:
print os.path.isfile(line)
f.close()
执行错误,即使对于文件的路径,print语句返回False !!!(我猜问题是os.path无法在单引号中取行变量)所以任何人都可以帮我纠正代码?
答案 0 :(得分:1)
1)删除行尾(又名。\n
)
如果您逐行阅读,则最后一个字符将是\n
(表示"换行符")。你可以删除它:
path = line[:-1] # take every character of 'line' except the last one
或者如果您想要更安全的解决方案:
def remove_newline(str):
return str.replace('\n', '').replace('\r', '')
path = remove_newline(line)
这也会删除某些系统使用的\r
。 (更多信息:Newline, wikipedia)
2)检查path
类型
Python为您提供了两个函数:来自os.path
(doc),即:
os.path.isfile(path)
os.path.isdir(path)
3)所以看起来应该是这样的:
import os
f = open('sample.txt','r')
for line in f:
path = remove_newline(line)
if os.path.isdir(path):
print("Its a directory!")
elif os.path.isfile(path):
print("Its a regular file!")
else:
print("Hmmm it looks like its not a correct path!")
f.close()
希望有帮助
pltrdy
答案 1 :(得分:-1)
尝试跳转到该路径,如果发生错误,则它不是路径。 另外,使用.strip(“\ n”)也可以删除路径中除换行符之外的其他部分
import os
f = open("sample.txt","r")
for line in f:
try:
path = line[0:len(line)-1] #removes the '\n' character
os.chdir(path)
print(True)
except: #when it tries to change it's directory to something invalid
print(False)
f.close()
答案 2 :(得分:-1)
如果您在分隔字符(例如<>
)中打印每一行,您会看到在for line in f
中读取的行以新行字符(\n
)结尾。此外,您可以比较剥离前后的行以调试是否需要剥离:
import os
f = open('sandbox.txt','r')
lineNo = 0
for line in f:
lineNo += 1
lineStripped = line.strip()
print("Line %d before stripping: <%s>" % (lineNo, line))
print("Line %d after stripping: <%s>" % (lineNo, lineStripped))
needStrip = (line != lineStripped)
print("Line %d needs stripping: %s" % (lineNo, needStrip))
isFile = os.path.isfile(lineStripped)
print("Line %d is file: %s" % (lineNo, isFile))
f.close()
为我输出:
Line 1 before stripping: </media/arjith007/Education/$RECYCLE.BIN
>
Line 1 after stripping: </media/arjith007/Education/$RECYCLE.BIN>
Line 1 needs stripping: True
Line 1 is file: False
Line 2 before stripping: </media/arjith007/Education/.Trash-1000
>
Line 2 after stripping: </media/arjith007/Education/.Trash-1000>
Line 2 needs stripping: True
Line 2 is file: False
Line 3 before stripping: </media/arjith007/Education/output.txt>
Line 3 after stripping: </media/arjith007/Education/output.txt>
Line 3 needs stripping: False
Line 3 is file: False
在剥离前打印值时,在下一行显示结束标记(>
)表示该行以其尾随的新行读取。