简体   繁体   中英

How to get the contents of multiple dynamic text files and store it in one text file and in mysql - Python 2.7?

I have multiple text file in my import folder where, I want to read all of the lines for each text file and store it in one text file only. I am just going to test if all lines are read by python and eventually i will store it in mysql database. How do I do that using fileinput? i cannot seem to start, my files are dynamic: here is my code:

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

I tested using this one, but it fails..

  with fileinput.input(files=(pathNow, pathYesterday)) as f:
       for line in f:
          //HOW TO OUTPUT TO TEXT FILE?

For now i dont have a problem for mysql, but if you could point me to a good tutorial, for now i read this one, seems to be fine: http://www.jeremymorgan.com/tutorials/python-tutorials/how-to-connect-to-mysql-with-python/

edit: I am using python 2.7, How to get the contents of multiple dynamic text files and store it in one text file and in mysql?

I hope this will help someone...

# 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())    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM