![](/img/trans.png)
[英]How to change actual location to temporary, add headers and remove space in csv file on Python Email table from MySQL?
[英]Python, how to get the actual file location
使用 python 3:如何獲取文件的路徑? 請檢查以下代碼:
path =r'\\Desktop'
os.chdir(path)
for root, dirs, files in os.walk(path):
for txt_file in files:
if txt_file.endswith(".txt"):
txt_fileSh=txt_file.rstrip(".txt")
path_txt_file=os.path.abspath(txt_file)
print(path_txt_file)
我得到的是
\\Desktop\a.txt
\\Desktop\b.txt
...我應該得到什么:
\\Desktop\Fig1\a.txt
\\Desktop\Fig2\b.txt
非常感謝您的幫助。
您不需要更改目錄。 您可以構建基於行走根的完整路徑,如下所示:
path = r'\Desktop'
import os
for root, _, files in os.walk(path):
for file in files:
if file.endswith('.txt'):
print(os.path.join(root, file))
abspath
的 文檔指出:
os.path.abspath(path)
Return a normalized absolutized version of the pathname path. On most
platforms, this is equivalent to calling the function normpath() as follows:
normpath(join(os.getcwd(), path)).
所以,你實際上只是將你的path
與文件名連接起來。
您想要使用當前目錄的路徑,這是os.walk
返回的三個項目中的第一個,您將其命名為root
。
所以,只需更換
path_txt_file=os.path.abspath(txt_file)
和
path_txt_file = os.path.join(root, txt_file)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.