Forceme
Forceme

Reputation: 1

Read csv lines and save it as seperate txt file, named as a line - python

i have some problem with simple code. I have a csv file with one column, and hundreds rows. I would like to get a code to read each line of csv and save it as separate txt files. What is important, the txt files should have be named as read line.

Example: 1.Adam 2. Doroty 3. Pablo

will give me adam.txt, doroty.txt and pablo txt. files. Please, help.

Upvotes: 0

Views: 818

Answers (2)

brc
brc

Reputation: 269

Alternatively you can use built-in CSV library to avoid any complications with parsing csv files:

import csv
with open('names.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        file_name ='{0}.txt'.format(row['first_name'])

        with open(file_name, 'w') as f:
            pass

Upvotes: 0

Daniel Lee
Daniel Lee

Reputation: 8011

This should do what you need on python 3.6

with open('file.csv') as f:       # Open file with hundreds of rows 
    for name in f.read().split('\n'):  # Get list of all names
        with open(f'{name.strip()}.txt', 'w') as s:  # Create file per name
            pass

Upvotes: 1

Related Questions