简体   繁体   English

Python pandas 读取 .txt 文件并使用分隔列导出 .csv

[英]Python pandas read .txt files and export .csv with separating colums

i have a problem, i tried to read a .txt file and exported to .csv and separating the lines using a delimiter by colums using categories.我有一个问题,我试图读取一个 .txt 文件并导出到 .csv 并使用分隔符通过使用类别的列分隔行。

file.txt is like this file.txt是这样的

[groups] 
admins = user1,user2,user3 
users_network = user4,user5 
users_m4s = user6,user7,user8,user9 

and the .csv file should be并且.csv文件应该是

groups

user1 = admins
user2 = admins
user3 = admins
user4 = users_network
user5 = users_network
user6 = users_m4s ... for the rest of element of category line

i tried我试过了

import pandas as pd
import numpy as np

df = pd.read_table("D:\GIT-files\Automate-Stats\SVN_sample_files\sample_svn_input.txt" , sep='\=',engine='python')
print(df)

df.to_csv("D:\GIT-files\Automate-Stats\SVN_sample_files\sample_svn_input_update.csv" , index=None)

df = pd.read_table ("D:\GIT-files\Automate-Stats\SVN_sample_files\sample_svn_input_update.csv" , sep='\=',engine='python')
print(df)

but its not creating right the .csv and display但它没有创建正确的 .csv 并显示

I was able to get the results you needed based on the provided code with this line of code我能够使用这行代码根据提供的代码获得您需要的结果

df = pd.read_csv(r"D:\GIT-files\Automate-Stats\SVN_sample_files\sample_svn_input.txt", sep = '|')
df.columns = ['groups']
df['New Columns'] = df['groups'].apply(lambda x : x.split('=')[0])
df['groups'] = df['groups'].apply(lambda x : ' '.join(x.split('=')[1:]))
df['groups'] = df['groups'].apply(lambda x : x.split(','))
df = df.explode('groups')
df['groups'] = df['New Columns'] + ' = ' + df['groups']
df = df[['groups']]
df.to_csv("D:\GIT-files\Automate-Stats\SVN_sample_files\sample_svn_input_update.csv" , index = False)

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

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