Re: [問題] 用file open抓TXT開的問題

作者: doomleika (iSuck)   2016-05-02 03:08:41
※ 引述《QooEX (QooEX)》之銘言:
: 我有大量的TXT檔案想用 file= open('xxx'.'r')
: 讀取近來全部放到list內部排序
: 問題來了 前面xxx的部分 我是用抓內部資料夾全部的檔名出來去設置
: 所以'' 以我目前的知識跟常識來說 是不可能放變數的
: 例如:我將檔名抓出來 找個空間放 A=檔名 但是不可能放進''內
: 所以我的解決想法是
: ccc=os.listdir('C:/new')[0]
os.listdir包含了資料夾,如果你的檔案資料夾裡面包含子資料夾的話可能會爆炸
(IsADirectoryError)
可以考慮使用os.walk[1]或是使用os.listdir[2]配合os.path.isfile驗證
[1] https://docs.python.org/2/library/os.html#os.walk
[2] https://docs.python.org/2/library/os.path.html#os.path.isfile
: def new(str):
: return "%s%s%s" %('\'C:/new/',ccc,'\'')
你的問題出在字串的處理上:
Python用雙引號或是單引號去表示字串,單雙引號是寫給Python看的,再加'(\')是告訴
Python你希望在字串表示單引號,所以假設你的ccc變數是"ccc"上面的程式結果會是
'C:/new/ccc'
^ ^
前後這單引號被當程檔案的路徑的一部分了,所以會出錯
你應該寫成:
def new(ccc):
return "%s%s" %("C:/new/",ccc)
字串連結能寫得更簡潔:
def new(ccc):
return "C:/new/" + ccc
關於檔案路徑Python有提供os.path.abspath跟os.path.join幫你處理,所以這段能寫成
from os.path import join, abspath
def get_path(directory, file):
return abspath(join(directory, file))
: file1 = open(new(ccc),r)
: 上面去呼叫的
: 有print出來看 是正確的'位址 '
: 置換出 error前面出現顯示的路徑
: 直接替換 我上面new地方也是可以執行的
: 請問是哪裡有錯
: 或是有甚麼方式可以解決
綜合前面的資訊,你可以寫成
import os
from os.path import join, abspath
def get_path(directory, file):
return abspath(join(directory, file))
# Put your directory here
directory = "C:/path/to/your/directory"
directories = os.walk(directory)
text_list = []
for directory, _, files in directories:
for a_file in files:
file_path = get_path(directory, a_file)
with open(file_path, 'r') as f:
text_list.append(f.read())
這樣跑完text_list應該就是你要的結果
作者: uranusjr (←這人是超級笨蛋)   2016-05-02 03:51:00
每次看到這種程式就要推一次 Python 3, 寫起來簡單多了
作者: doomleika (iSuck)   2016-05-02 10:34:00
請問Python 3要怎麼寫 ._.?
作者: QooEX (QooEX)   2016-05-02 16:51:00
感謝願意花這麼多時間回文><真的超厲害 ~再推一次

Links booklink

Contact Us: admin [ a t ] ucptt.com