所以我想要在For循環中使用全局變量。此代碼工作時沒有錯誤,而不是在一個函數「def」,但我需要它,因爲我試圖創建一個tkinter文件對話框,一旦選擇文件,如果你可以幫助告訴我我在做什麼錯誤或給我一個替代使用tkinter和「def」。Python3如何爲「For」循環聲明全局變量
工作代碼:
import os
import sqlite3
from datetime import datetime
# import datetime
import itertools
from dateutil.relativedelta import relativedelta
date = datetime.strptime('1991-01-01', '%Y-%m-%d')
f_path = 'C:/Users/Lewis Collins/Job_Code/data/cru_ts_2_10.1991-2000_cutdown.pre'
# db = sqlite3.connect('output.db')
# cursor = db.cursor()
# cursor.execute('CREATE TABLE Rainfall (Xref, Yref, Date, Value)')
# date = datetime.date(1991,1,1)
flag = 0
Xref = ''
Yref = ''
with open(f_path) as file_read:
for row in itertools.islice(file_read, 5, None):
# print(row)
if 'Grid-ref' in row:
Xref = row.split(',')[0].split('= ')[1]
Yref = row.split(',')[1]
date = datetime.strptime('1990-12-01', '%Y-%m-%d')
else:
for Value in row.split():
date = date + relativedelta(months=+1)
# print(Xref.strip(), Yref.strip(), date, Value)
# print(Xref, Yref, date, Value)
# db.commit()
# db.close()
編輯代碼:只要不建議使用全局變量
import tkinter
from datetime import datetime
from dateutil.relativedelta import relativedelta
import itertools
#date = datetime.strptime('1991-01-01', '%y-%m-%d')
# date = datetime.strptime('1991-01-01', '%Y-%m-%d')
f_path = 'C:/Users/Lewis Collins/Job_Code/data/cru_ts_2_10.1991-2000_cutdown.pre'
Xref = ''
Yref = ''
def read_date():
with open(f_path) as file_read:
for row in itertools.islice(file_read, 5, None):
if 'Grid-ref' in row:
Xref = row.split(',')[0].split('= ')[1]
Yref = row.split(',')[1]
date = datetime.strptime('1990-12-01', '%y-%m-%d')
else:
for Value in row.split():
date = date + relativedelta(months=+1)
print(Xref.strip(), Yref.strip(), date, Value)
請勿使用全局變量。反而有你的函數'返回'結果。 – spectras