简体   繁体   English

读取文本文件并在Python中创建csv文件

[英]Read the text file and create csv file in Python

I want to read multiple text files and create one csv file. 我想读取多个文本文件并创建一个csv文件。 its like header line is common, read data from each file and create one line in csv. 它的标题行很常见,它从每个文件读取数据并在csv中创建一行。

input file is like. 输入文件就好。

readme_1006999-111418.html0000664077736200007070000001676613373210077014576

\--------------GENERAL INFO --------------------
CR ID #: 1006999-111418
Product Version: 10.1.10.1.5
Case ID #: 1012440-102118
\--------------Short description----
DS | Cleanup TEST| crashed on after run the admin command
\------ New/Modified files ------
Customer.cpp
input.cpp
output.cpp
\------ Affected executables and libraries ------
classes.jar
info.so
function.so
messageinfo.so

i want output like 我想要输出像

GENERAL INFO,Short description,Affected executables and libraries
CR ID #: 1006999-111418 Product Version: 10.1.10.1.5 Case ID #: 1012440-102118, DS | Cleanup TEST| crashed on after run the admin command,Customer.cpp input.cpp output.cpp,classes.jar info.so function.so messageinfo.so

on next line i want three line under "GENERAL INFO" then comma, same for other headers. 在下一行中,我要在“ GENERAL INFO”下输入三行,然后用逗号分隔,其他标题相同。

i tried small code with help of google as i am new in python. 我在google的帮助下尝试了小代码,因为我是python的新手。

import csv
import os
import glob

#for filename in glob.glob(os.path.join('/bd_users/abpwrk1/OM/AM/Lab', '*.txt')):
with open('test.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line.split(",") for line in stripped if line)
    with open('output.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('GENERAL INFO', 'Short description','New/Modified files','Affected executables and libraries','Affected executables and libraries','DETAILED INFO','Detailed Problem Description','Solution','Testing Instructions','ADDITIONAL IMPACT','Database Changes','Environment Notes','XPI/Topology Changes'))
       writer.writerows(lines)

can someone pls help to write the logic which will print all the lines under header(enclosed -------header----)in single cell. 有人可以帮忙编写逻辑,该逻辑将在单个单元格中打印标头(封闭的------- header ----)下的所有行。

Try something like that, hope this will help you 尝试类似的方法,希望对您有所帮助

Parse a plain text file into a CSV file using Python 使用Python将纯文本文件解析为CSV文件

import csv
import itertools

with open('extracted.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line for line in stripped if line)
    grouped = itertools.izip(*[lines] * 3)
    with open('extracted.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro', 'tagline'))
        writer.writerows(grouped)

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

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