如何逐行读取多个文本文件,并发送到Excel每个文件后移动到一个新的列?

我build立一个脚本运行重复testing,每个日志文件将被读取和编译到电子表格。

每个文件和行的数量将根据时间和期望的演变而变化。 我有一个基本的脚本,逐行读取一个文件,并将数据粘贴到一个单独的excel文件中连续的行。

from openpyxl import load_workbook from Test_Parameters import Results_Name from Downstream import Log_Angle wb = load_workbook(filename= Results_Name +'.xlsm', read_only=False, keep_vba=True) ws7 = wb['timeData'] FILE = open('0_Downstream.txt', 'r+') line = FILE.readline() N = '2' while line !="": print(line) ws7['A'+N] = line line = FILE.readline() N = float(N) N = (N+1) N = "%g" % N wb.save(Results_Name+'.xlsm') FILE.close() 

我需要能够通过在同一目录中的多个文件循环,并把结果放在一个单独的列比最后一个。 类似于下面的表格: Excel布局

谢谢你的帮助。

不要使用ws['A'+N]进行编程访问。

我认为以下可能接近你想要的:

 col_idx = ws.max_column + 1 for row_idx, line in enumerate(file, 1): if line == "": break ws.cell(row=row_idx, col=col_idx, value=line) wb.save(…) 
 import os cwd = os.getcwd() for filename in os.listdir(cwd): if filename.endswith(".txt"): with open('%s\\%s' % (cwd, filename), 'r+') as file: [DO STUFF] 

上面的代码允许你迭代当前工作目录中的多个文件(一个指定的types)。

这有帮助吗?

我和卢克的想法一样(只是花了一点时间打字):

 from openpyxl import load_workbook from Test_Parameters import Results_Name from Downstream import Log_Angle import os def good_name(): wb = load_workbook(filename=Results_Name + '.xlsm', read_only=False, keep_vba=True) ws7 = wb['timeData'] for path in os.listdir('dir_path'): # You can use glob here if you have other extensions than .txt ws = load_sheet(path, ws7) wb.save(Results_Name + '.xlsm') def load_sheet(file_path, ws): with open(file_path, 'r+') as FILE: # This context manager is a cleaner way to open/close our file handle line = FILE.readline() N = '2' while line !="": print(line) ws['A'+N] = line line = FILE.readline() N = float(N) N = (N+1) N = "%g" % N return ws 
  1. 此示例读取test / txt中的所有文件
  2. 为每个文件使用一个新的列
  3. 文件名被分配到第1行
  4. 追加所有阅读行,从第2行开始

     # List all files in test/txt' dirName = os.path.join('test', 'txt') for column,fname in enumerate(os.listdir(dirName),1): # Column Title = Filename ws.cell(row=1, column=column, value=fname) # My Sample Text files are utf-8 encoded with io.open( os.path.join(dirName, fname),'r', encoding='utf8') as fh: # Column Data begins on Row 2 for row,line in enumerate(fh,2): ws.cell(row=row, column=column, value=line) #end with = closing fh #end for 

    用Pythontesting:3.4.2 – openpyxl:2.4.1 – LibreOffice:4.3.3.2 *