[爆卦]Python 檔名 變數是什麼?優點缺點精華區懶人包

為什麼這篇Python 檔名 變數鄉民發文收入到精華區:因為在Python 檔名 變數這個討論話題中,有許多相關的文章在討論,這篇最有參考價值!作者doomleika (iSuck)看板Python標題Re: [問題] 用file open抓T...


※ 引述《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應該就是你要的結果

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.126.153.159
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1462129725.A.7DA.html
※ 編輯: doomleika (59.126.153.159), 05/02/2016 03:11:34
※ 編輯: doomleika (59.126.153.159), 05/02/2016 03:17:45
uranusjr: 每次看到這種程式就要推一次 Python 3, 寫起來簡單多了 05/02 03:51
doomleika: 請問Python 3要怎麼寫 ._.? 05/02 10:34
QooEX: 感謝願意花這麼多時間回文>< 05/02 16:51
QooEX: 真的超厲害 ~再推一次 05/02 17:00

你可能也想看看

搜尋相關網站