简体   繁体   English

如何逐行读取多个文本文件并在每个文件后发送到excel移动到新列?

[英]How to read multiple text files line by line and send to excel moving to a new column after every file?

Im building a script to run duplicate tests each with a log file that will be read and compiled into a spreadsheet. 我正在构建一个脚本来运行重复测试,每个测试都有一个日志文件,该文件将被读取并编译成电子表格。

The number of files and lines in each will vary depending on time and desired itterations. 每个文件和行的数量将根据时间和所需的迭代而变化。 I have a basic script to read one file line by line and paste the data into a seperate excel document in successive rows. 我有一个基本脚本,逐行读取一个文件,并将数据粘贴到连续行的单独的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()

I need to be able to get this to cycle through multiple files in the same directory and put the results in a seperate column than the last. 我需要能够让它循环遍历同一目录中的多个文件,并将结果放在一个单独的列中,而不是最后一个。 Similar to the sheet below: Excel Layout 与下表相似: Excel布局

Thanks for any help. 谢谢你的帮助。

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]

The above code allows you to iterate over multiple files (of a specified type) in the current working directory. 上面的代码允许您迭代当前工作目录中的多个文件(指定类型)。

Does this help? 这有帮助吗?

I was thinking along the same terms as Luke (just took a bit longer typing): 我正在和Luke一样思考(只需要更长时间的打字):

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

Don't use ws['A'+N] for programmatic access. 不要使用ws['A'+N]进行编程访问。

I think the following is probably close to what you want: 我认为以下内容可能与您想要的相近:

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(…)
  1. This Sample reads all files in test/txt 此示例读取test / txt中的所有文件
  2. Uses for every file a new Column 用于每个文件的新列
  3. Filename are assigned to Row 1 文件名分配给第1行
  4. Appends all reading lines, begining at Row 2 附加所有阅读行,从第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 

    Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice: 4.3.3.2* 用Python测试:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2 *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将文件的每一行保存到一个新文件(每一行一个新文件)并为多个原始文件执行此操作 - How to save each line of a file to a new file (every line a new file) and do that for multiple original files 如何从Excel读取数据并逐行将其写入文本文件? - How to read data from Excel and write it to text file line by line? 读取每隔一行并打印到新文件 - Read every second line and print to new file 如何逐行读取CSV文件并将其存储到新行的新CSV文件中? - How to read a CSV file line by line and store it to new CSV file on new row every time? 为文本文件中的每一行创建一个新列表? - Creating a new list for every line in a text file? 如何读取CSV或文本文件的行,循环遍历每行并保存为每行读取的新文件 - How To Read Lines of CSV or Text File, Loop Over Each Line and Save To a New File For Each Line Read 如何在python中逐行读取文本文件 - how to read text file line to line in python 如何读取文本文件中的一行,提取 substring 并返回一列? - How to read a line in text file, extract substring and return to a column? 如何只读取文件的第二行? - How to read in only every second line of file? 如何在 python 中的空格后读取文本文件的每一行 - How to Read text file each line after space in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM