[英]Using os.walk to find and print names of my files, but unable to open them? Path name issue?
我的相關代碼塊如下:
path = "\\Users\\Harmless\\Documents\\untitled"
cellorder = []
cellcont = []
for roots, dirs, files, in os.walk(path):
for file in natural_sort(files):
if "Row" in file:
cellorder.append(file)
with open(file,'r') as txt:
print txt.readlines
#print "file = %s" % file
這將成功列出我要打開的所有文件(如注釋掉),但是當我嘗試以與打印文件名相同的方式傳遞文件名以讀取文件時:
IOError: [Errno 2] No such file or directory: 'Row0Col0Heat.txt'
我怎樣才能解決這個問題? 我需要在每個文件名中引用整個路徑名和字符串替換嗎? 如果是這樣,為什么? 有沒有更好的方法來引用/利用路徑?
嘗試使用文件的絕對路徑,可以通過以下方式獲取絕對路徑
abs_file_path = os.path.abspath(file)
因為您已經有了基本路徑,所以也可以使用:
abs_file_path = os.path.join(path, file)
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.