Home > Mobile >  Python pandas read .txt files and export .csv with separating colums
Python pandas read .txt files and export .csv with separating colums

Time:06-07

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.

file.txt is like this

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

and the .csv file should be

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

CodePudding user response:

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)
  • Related