[英]How Can You Get a File out from a Directory in Python?
我在 python 中聲明一個變量:
e = ('file.txt', 'r')
但是該文件在一個目錄中,我不知道如何編寫它以便它會在我的目錄 playergold 中查找。 我試過
playergold = 'PlayerFiles/PlayerGold'
e = open('playergold/gold.1.txt', 'r')
和
e = open(from playergold import gold.1.txt', 'r')
和
e = open(playergold/'gold.1.txt', 'r')
但兩者都不起作用。 (順便說一句,我從問題Loop Through A Folder in Python 中得到了這段代碼)
目錄樹如下所示:
代碼包含methods.py,這是所有代碼的地方。
PlayerFiles 包含文件夾 PlayerGold 和 PlayerItems
PlayerGold 包含 gold.1.txt
PlayerFiles 和 Code 處於同一級別。
你能幫忙的話,我會很高興。 謝謝你的時間!
看起來你需要。
import os
with open(os.path.join('PlayerFiles','PlayerGold', 'gold.1.txt')) as infile:
data = infile.read()
#process
確保路徑正確並嘗試以正確的形式傳遞它 - 始終記得打開一個封閉的引號。
e = open('playergold/gold.1.txt', 'r')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.