I have a csv file with multiple rows with this structure
name lastname group password
john smith sales abc1
liza jones hr abc2
The list is around 500 rows long, and I would like to create a txt file with this structure
- name: j.smith
password: abc1
groups: admins
I want to reproduce spacing, so before the "-" character you will see there are 2 spaces, and five spaces before password as this is needed in the final txt file.
CodePudding user response:
While in general you should not use pandas iterrows, because it is very slow, I am going to use it in my answer in part because you do not need to use pandas at all: you just want to iterate over the rows in your CSV:
import pandas as pd
df = pd.DataFrame.from_dict({'name': {0: 'john', 1: 'liza'}, 'lastname': {0: 'smith', 1: 'jones'}, 'group': {0: 'sales', 1: 'hr'}, 'password': {0: 'abc1', 1: 'abc2'}})
template = """- name: {fname[0]}. {lname}
password: {pword}
groups: {groups}
"""
with open('output.txt', 'w') as fp:
# iterrows returns the index, which we ignore with _
for _, (name, lastname, group, password) in df.iterrows():
fp.write(template.format(fname = name, lname = lastname, pword = password, groups = group))
Here we use a template string that we will substitute the values into using keyword arguments in the string format method. This will write the output to output.txt. Notice the keywords correspond directly to the keywords used in the template. The resulting text file appears as:
- name: j. smith
password: abc1
groups: sales
- name: l. jones
password: abc2
groups: hr
