-2

I am trying to read a file in Python using the below code:

with open(file) as fp:
    data = fp.read()

The above script works well. I however am trying to have the filename included in the output of data

How could I have that included.

Edit:

Adding a sample output with the expected result

Current Output:

col1,col2,col3
1,Prod_A,10
2,Prod_B,5

Expected output:

col1,col2,col3,filename
1,Prod_A,10,sales.csv
2,Prod_B,5,sales.csv
scott martin
  • 1,253
  • 1
  • 14
  • 36

2 Answers2

0

It might be something as simple as

data = {}

with open("test.txt") as fp:
   data['name'] = fp.name
   data['content'] = fp.read()

the output would look something like

{'name': 'test.txt',
 'content': '124512451245124512451245124512451245124512451245\n'}

But it really depends on what you want the structure of data to be.

Edit: based on the feedback, the example above can be rewritten with a list as

data = []

with open("test.txt") as fp:
   data.append(fp.name)
   data.append(fp.read())

the output would look like:

['test.txt', '124512451245124512451245124512451245124512451245\n']
not link
  • 858
  • 1
  • 16
  • 29
0

Read your csv file and add new column:

import csv
import os

m, n = 'sales.csv', 'sales_temp.csv'

with open(m, newline='') as f:
    with open(n, 'w', newline='') as f_temp:
        w = csv.writer(f_temp)

        for r in csv.reader(f):
            w.writerow(r + ['filename']) if r[0] == 'col1' else w.writerow(r + [f.name])

os.remove(m)
os.rename(n, m)
Camile
  • 107
  • 5