![](/img/trans.png)
[英]How to take full windows file path as user input and work with the file
[英]How to take directory path as a user input on Windows?
我正在嘗試開發一個UI,該UI允許用戶打開菜單,設置目錄,輸入文件名(word doc)並對文件執行一組任務,並將新修改的文件保存在與該文件相同的目錄/位置中舊文件。
但是,嘗試設置目錄時,我立即收到錯誤消息。 這是我的代碼:
def menu():
""" the main user-interaction loop
"""
Cuts = ""
while True:
display_menu()
choice = int(input('Enter your choice: '))
print()
if choice == 0:
print('input directory')
x = input()
os.chdir(x)
嘗試執行此操作時出現以下錯誤:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: "'C:\\Users\\NAME\\Desktop'"
考慮到當我直接在腳本/它可以工作的shell上執行操作時,這太奇怪了!
實際上,我的代碼的第一行是:os.chdir(C:/ Users / NAME / Desktop')-效果很好。
我知道對於Windows,關於“ /”是轉義符的討論-我部分理解這個概念,但是我已經嘗試使用“ \\”而不是“ /”或使用“ //”的多種選擇。 還研究了使用raw_input,但我使用的是3.6,因此該功能甚至無法正常工作。
任何見解/幫助將不勝感激! 謝謝!!
根據您的錯誤消息:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: "'C:\\Users\\NAME\\Desktop'"
我猜您在input
提示中輸入了'C:\\Users\\NAME\\Desktop'
。 省略引號( ''
),然后就可以了。
否則,您最終將把此字符串傳遞給os.chdir
: "'C:\\Users\\NAME\\Desktop'"
,這不是有效路徑。
使用Os原語,您的代碼將類似於:
x = input()
path = os.path.join(os.getcwd(), x)
os.chdir(path)
這將從當前目錄導航
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.