2014-02-14 18 views
0

有人可以幫我解釋一下Python中的文件路徑問題嗎?Python在不同的本地驅動器位置讀取文件

例如我的代碼需要讀取一個批處理文件,文件名中列出,並存儲在一個.txt文件,C:\ Filelist.txt中,其內容是:

C:\1stfile.txt 
C:\2ndfile.txt 
C:\3rdfile.txt 
C:\4thfile.txt 
C:\5thfile.txt 

而且代碼開始於:

list_open = open('c:\\aaa.txt') 
read_list = list_open.read() 
line_in_list = read_list.split('\n') 

一切正常。但是如果我想在另一個路徑中讀取文件,例如:

C:\WorkingFolder\6thfile.txt 
C:\WorkingFolder\7thfile.txt 
C:\WorkingFolder\8thfile.txt 
C:\WorkingFolder\9thfile.txt 
C:\WorkingFolder\10thfile.txt 

它不起作用。我猜這裏的路徑C:\ WorkingFolder \沒有正確放置,所以Python無法識別它。

那麼我會以什麼方式把它呢?謝謝。




您好所有,

抱歉,也許我沒有讓我自己清楚。

的問題是,一個文本文件,C:\ aaa.txt下面包含:

C:\1stfile.txt 
C:\WorkingFolder\1stfile.txt 

爲什麼只有C:\ 1stfile.txt是可讀的,但是另外一個呢?

+0

是否所有的字符串正確轉義,即「 」C:\\ \\ WorkingFolder 10thfile.txt「'或'R 」C:\ WorkingFolder \ 10thfile.txt「'? – SethMMorton

回答

2

你的程序不工作的原因是你沒有正確改變目錄。使用os.chdir()這樣做,然後再打開文件正常:

import os 

path = "C:\\WorkingFolder\\" 

# Check current working directory. 
retval = os.getcwd() 

print "Current working directory %s" % retval 

# Now change the directory 
os.chdir(path) 

# Check current working directory. 
retval = os.getcwd() 

print "Directory changed successfully %s" % retval 

參考: http://www.tutorialspoint.com/python/os_chdir.htm

1

簡單地嘗試使用正斜槓來代替。

list_open = open("C:/WorkingFolder/6thfile.txt", "rt") 

它適合我。

2
import os 

BASEDIR = "c:\\WorkingFolder" 

list_open = open(os.path.join(BASEDIR, 'aaa.txt')) 
+0

感謝您的回覆,這也有幫助。 –

相關問題