[英]Python: Use local variable globally does not work
在任一操作系統中搜索文件后,我正在嘗試使用我的代碼打開文件。 但是,當我在 function 中分配變量時,我無法在 function 之外使用它。 當我將第二個 function 保留在第一個 function 之外時,它無法識別 function。
我嘗試全局分配 df_location ,但這不起作用。 當我在 function 中使用df = pd.read_csv(df_location[0], index_col=0)
時,我無法在代碼中的其他任何地方使用 df。
if platform.system() == 'windows':
def find_file(root_folder, rex):
for root, dirs, files in os.walk(root_folder):
for f in files:
result = rex.search(f)
if result:
file_path = os.path.join(root, f)
return file_path
def find_file_in_all_drives(file_name):
matching_files = list()
# create a regular expression for the file
rex = re.compile(file_name)
for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]:
file_path = find_file(drive, rex)
if file_path:
matching_files.append(file_path)
return matching_files
global df_location
df_location = find_file_in_all_drives("AB_NYC_2019.csv")
if platform.system() == 'mac':
df_location = find_file("/", "AB_NYC_2019.csv")
df = pd.read_csv(df_location[0], index_col=0)
我希望能夠使用通過函數檢索到的文件。
謝謝!
理想情況下應該是這樣的
if platform.system() == 'windows':
def find_file(root_folder, rex):
for root, dirs, files in os.walk(root_folder):
for f in files:
result = rex.search(f)
if result:
file_path = os.path.join(root, f)
return file_path
def find_file_in_all_drives(file_name):
matching_files = list()
# create a regular expression for the file
rex = re.compile(file_name)
for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]:
file_path = find_file(drive, rex)
if file_path:
matching_files.append(file_path)
return matching_files
df_location = find_file_in_all_drives("AB_NYC_2019.csv")
if platform.system() == 'mac':
df_location = find_file("/", "AB_NYC_2019.csv")
df = pd.read_csv(df_location[0], index_col=0)
但這會給出錯誤消息:“NameError: name 'find_file_in_all_drives' is not defined”
您沒有顯示所有代碼。 據推測,您也有適用於 mac 的find_file
和find_file_in_all_drives
function 實現,是嗎? 至少這是我通過查看您發布的代碼所期望的。
如果這確實是您擁有的所有代碼,那么按照現在的編寫方式,您只需定義find_file
和find_file_in_all_drives
如果platform.system()
返回“windows”(旁注:剛剛嘗試過,在我的 Windows 7 系統上它返回帶有大寫“W”的“Windows”。)如果不滿足該條件,則這些 function 定義在代碼中的其他任何地方都不可見,因為您已將它們放在 if 語句的主體中。
看起來您正試圖根據字符串( platform.system()
)的內容獲得不同的行為。 由於您無法避免必須為兩個操作系統實現不同的行為,因此您可以為此使用多態性:
import abc
class DataFrameFinder(abc.ABC):
def __init__(self):
pass
@abc.abstractmethod
def find_file(self, root_folder, rex):
raise NotImplementedError
@abc.abstractmethod
def find_file_in_all_drives(self, file_name):
raise NotImplementedError
class DataFrameFinderWindows(DataFrameFinder):
def __init__(self, *args, **kwargs):
DataFrameFinder.__init__(self, *args, **kwargs)
def find_file(self, root_folder, rex):
# Do windows things...
pass
def find_file_in_all_drives(self, file_name):
# Do windows things...
pass
class DataFrameFinderMac(DataFrameFinder):
def __init__(self, *args, **kwargs):
DataFrameFinder.__init__(self, *args, **kwargs)
def find_file(self, root_folder, rex):
# Do mac things...
pass
def find_file_in_all_drives(self, file_name):
# Do mac things...
pass
def main():
import platform
finder_factory = {
"Windows": DataFrameFinderWindows,
"Mac": DataFrameFinderMac
}
finder = finder_factory[platform.system()]()
finder.find_file(...)
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
您為Window
定義find_file_in_all_drives
但您也應該為其他系統定義find_file_in_all_drives
- 但每個系統在find_file_in_all_drives
中都有不同的代碼。 然后您可以在每個系統上使用find_file_in_all_drives
# all systems use it so it should be defined for all
def find_file(root_folder, rex):
for root, dirs, files in os.walk(root_folder):
for f in files:
result = rex.search(f)
if result:
file_path = os.path.join(root, f)
return file_path
# define different `find_file_in_all_drives` for different systems
if platform.system() == 'windows':
def find_file_in_all_drives(file_name):
matching_files = list()
# create a regular expression for the file
rex = re.compile(file_name)
for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]:
file_path = find_file(drive, rex)
if file_path:
matching_files.append(file_path)
return matching_files
if platform.system() in ('mac', 'linux'):
def find_file_in_all_drives(file_name):
return find_file("/", file_name)
# now you can use `find_file_in_all_drives` on every system
df_location = find_file_in_all_drives("AB_NYC_2019.csv")
df = pd.read_csv(df_location[0], index_col=0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.