[英]In Python, import a function using globals()
我有函數“ read_csv”,該函數經常在其他Python腳本中使用。 與其將其復制到我在其中使用的每個Python腳本的開頭,不如將其保存在單獨的文件中並導入。 該函數定義如下:
import numpy as np
def read_csv(filename,suffix=''):
# Read column headers (to be variable naames)
with open(filename) as f:
firstline = f.readline() # Read first line of csv
firstline = firstline.replace("\n","") # Remove new line characters
firstline = firstline.replace(" ","") # Remove spaces
ColumnHeaders = firstline.split(",") # Get array of column headers
# Read in the data (omitting the first row containing column headers)
data=np.genfromtxt(filename,skiprows=1,delimiter=",",filling_values=0)
# Assign the data to arrays, with names of the variables generated from column headers
Ind=0
for Var in ColumnHeaders:
VarName=Var+suffix # Define variable name appended with given suffix (if any)
globals()[VarName]=data[:,Ind] # Assign the columns of the data to variables names after the column headers
該函數讀取一個csv文件,其中包含列標題和其下的數字,並將這些數字作為數組寫入具有從列標題派生的名稱的“工作區”中。 我將上面的代碼保存為“ read_csv_nDI.py”。 在同一目錄中,我嘗試以下腳本:
import numpy as np
from read_csv_nDI import read_csv
read_csv('test.csv')
其中“ test.csv”是應正常工作的CSV文件:
Track, Bin, RO_T,ZEZ2A_T,Intra,RO_T_evnt_amp,ZEZ2A_T_evnt_amp,Intra_evnt_amp,Intra_reservoir_amplitude_normalized_to_RO_T,Intra_reservoir_amplitude_normalized_to_ZEZ2A_T
1, 1, 2149.7307, 2110.3000, 2189.5908, 1000.3883, -766.3962, -687.7489, -0.6875, 0.8974
1, 2, 2151.7307, 2112.3000, 2191.5908, 1000.3883, -766.3962, -687.7489, -0.6875, 0.8974
1, 3, 2153.7307, 2114.3000, 2193.5908, 1000.3883, -766.3962, -687.7489, -0.6875, 0.8974
1, 4, 2155.7307, 2116.3000, 2195.5908, 1000.3883, -766.3962, -687.7489, -0.6875, 0.8974
1, 5, 2157.7307, 2118.3000, 2197.5908, 1000.3883, -766.3962, -687.7489, -0.6875, 0.8974
1, 6, 2159.7307, 2120.3000, 2199.5908, 1000.3883, -766.3962, -687.7489, -0.6875, 0.8974
1, 7, 2161.7307, 2122.3000, 2201.5908, 1000.3883, -766.3962, -687.7489, -0.6875, 0.8974
但是,如果運行上述腳本並鍵入dir()命令,則不會看到我期望看到的變量“ RO_T”,“ ZEZ2A_T”等。 另一方面,如果我只是添加一行
read_csv('test.csv')
在同一個Python腳本中的函數定義之后,它可以工作,運行腳本后,我確實看到了這些變量。 為什么僅在函數定義在同一腳本中時才起作用?
globals
為您提供了在調用它的文件中的全局變量,因此它始終為您提供了定義了read_csv
的文件的全局變量。
這樣雜亂全局名稱空間可能不是最好的主意。 最好只返回整個數組。 另外,我建議您查看pandas
程序包,該程序包可以輕松地將CSV讀取到DataFrame對象中,該對象的作用類似於numpy數組,但對於大多數用途來說更方便。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.