使用Python仅将所需内容从文本文件复制到Excel

2024-10-06 09:00:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在文本文件中有一个巨大的数据,包括日期、学校名称、通过年份等详细信息,还包含学生的姓名和唯一id,如下所示。此外,文本文件未格式化,并且包含大量数据

Group list of all the students 
5 June 2020/KCT/2015 Group BRD Rahul e34 Pradeep e44 Venkat r45 Azhar t54  
6 June 2020/BCT/2012 Group ZRD Akash e14 Pavan e24 Vipul r15 Asad t14
7 June 2020/KBN/2014 Group KRD Fairoz e45 Kumar e55 Akshay e44 Vivek e99 etc

当我运行python代码时,我需要excel/csv表中的输出,其中只逐行显示名称(Column1)和唯一id(Column2)。基本上,在excel工作表中,我只希望在excel工作表中显示名称和唯一id,如下所示。我只需要显示名称和唯一id。我不需要excel工作表中的其他数据

Rahul    e34 
Pradeep  e44 
Venkat   r45 
Azhar    t54
Akash    e14 
Pavan    e24 
Vipul    r15 
Asad     t14
Fairoz   e45 
Kumar    e55 
Akshay   e44 
Vivek    e99

这就是我尝试过的

import pandas as pd
df = pd.read_csv("C:\Users\PMishra\Desktop\Document.txt", sep='\t' )
df.to_csv('C:\Users\PMishra\Desktop\Demo.csv')

当我运行这个程序时,它会将文本文件中的所有内容复制到excel工作表中。我希望在excel/csv表格中输出,其中逐行显示所有名称(第1列)和唯一ID(第2列)。我是python新手(Spyder)。如何分别在第1列和第2列中仅获取名称和ID


Tags: csv数据名称idgroupexcel文本文件june
2条回答

通过使用usecols参数see the Documentation.调用read_csv(),只能加载选定的列

# this would load only column 0, 1, and 2
# you can use column names too: ['col0', 'col1', 'col2']
dummy_example = pandas.read_csv('path_to/your_file.csv', usecols=[0, 1, 2])

然而,在你的情况下,我会在没有pandas的情况下做这件事

input_file = 'path_to/input_file.txt'
output_file = 'path_to/output_file.csv'

# open both files, output in "append" mode
with open(input_file, 'r') as file, open(output_file, 'a+') as out_file:
    for line in file.readlines():

       try:
            # split at 'Group'
            line = line.split('Group')[1]

            # split and select after Group name
            line = line.split()[1:]

        except:
            # no 'Group' or no data thereafter
            # skip to the next loop 
            continue

        # create name-id pairs
        name_id = list(zip(line[2::2], line[1::2]))

        for tup in name_id:
            # make comma separated string 
            string = ','.join(tup) + '\n'

            # append to the outfile 
            out_file.write(string)

输出文件

Pradeep,e34
Venkat,e44
Azhar,r45
Pavan,e14
Vipul,e24
Asad,r15
Kumar,e45
Akshay,e55
Vivek,e44
Pradeep,e34
Venkat,e44
Azhar,r45
Pavan,e14
Vipul,e24
Asad,r15
Kumar,e45
Akshay,e55
Vivek,e44

第一行必须是列的名称,然后只能显示两列的名称:

dfnew = df[["namecolum1","namecolum1"]]

dfnew.to_csv('C:\Users\PMishra\Desktop\Demo.csv')

相关问题 更多 >