[英]Read in multiple folder and combine multiple text files contents to one file per folder - Python
[英]How to get the contents of multiple dynamic text files and store it in one text file and in mysql - Python 2.7?
我的導入文件夾中有多個文本文件,我想讀取每個文本文件的所有行並將其僅存儲在一個文本文件中。 我只是要測試是否所有行都被python讀取,最終我會將其存儲在mysql數據庫中。 如何使用fileinput做到這一點? 我似乎無法啟動,我的文件是動態的:這是我的代碼:
for i in range(1, 4):
dateNow = datetime.datetime.today().date()
strNow = dateNow.strftime('%Y%m%d') + ".Dat"
cstrNow = pathA + str(i) + "\\" + strNow
dateYesterday = datetime.datetime.today().date() - timedelta(days = 1)
strYesterday = dateYesterday.strftime('%Y%m%d') + ".Dat"
cstrYesterday = pathA + str(i) + "\\" + strYesterday
try:
with open(cstrNow):
shutil.copy(cstrNow, pathImport + "\A" + str(i) + "_" + strNow)
pathNow = pathImport + "\A" + str(i) + "_" + strNow
except IOError:
print "No Dat file: " + pathImport + "\A" + str(i) + "_" + strNow
try:
with open(cstrYesterday):
shutil.copy(cstrYesterday, pathImport + "\A" + str(i) + "_" + strYesterday)
pathYesterday = pathImport + "\A" + str(i) + "_" + strYesterday
except IOError:
print "No Dat file: " + pathImport + "\A" + str(i) + "_" + strYesterday
for line in fileinput.input(pathNow):
print line
for line in fileinput.input(pathYesterday):
print line
我使用此工具進行了測試,但失敗了。
with fileinput.input(files=(pathNow, pathYesterday)) as f:
for line in f:
//HOW TO OUTPUT TO TEXT FILE?
目前,我對mysql沒有任何問題,但是如果您可以為我提供一個不錯的教程,那么現在閱讀此教程似乎還不錯: http : //www.jeremymorgan.com/tutorials/python-tutorials/how使用python /連接到MySQL /
編輯:我正在使用python 2.7,如何獲取多個動態文本文件的內容並將其存儲在一個文本文件和mysql中?
我希望這會幫助某人...
# READ ALL DAT FILE IN PATHIMPORT AND COMBINE INTO ONE TEXT FILE
strToday = dateToday()
read_files = glob.glob(pathImport + "\\" + "*.Dat")
with open("C:/swipeimport/" + "M_" + strToday + ".txt", "wb") as outfile:
for x in read_files:
with open(x, "rb") as infile:
outfile.write(infile.read())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.