0

我的导入文件夹中有多个文本文件,我想读取每个文本文件的所有行并将其仅存储在一个文本文件中。我只是要测试是否所有行都被python读取,最终我会将它存储在mysql数据库中。我如何使用文件输入来做到这一点?我似乎无法开始,我的文件是动态的:这是我的代码:

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 -to-connect-to-mysql-with-python/

编辑:我正在使用python 2.7,如何获取多个动态文本文件的内容并将其存储在一个文本文件和mysql中?

4

1 回答 1

0

我希望这会对某人有所帮助...

# 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())    
于 2013-10-22T08:28:28.733 回答