1

I am trying to write data in a file. Here is how I proceed.

values = [45, 67, 39]
with open(os.path.join(path_class, r'first_file.csv'), 'a') as f: 
writer = csv.writer(f)
        writer.writerow(values)

But I would like to have a variable at first_file.csv position.
My problem is here with open(os.path.join(path_class, r'file_name.csv')

So I would like to have something like:

list_of_file = ['first_file.csv', 'second_file.csv']
for i in range(0, len(list_of_file):
    with open(os.path.join(path_class, r+list_of_file[i]), 'a') as f:
        writer = csv.writer(f)
        writer.writerow(values)

How could I do that
Thank you for taking your time to answer my question.

Kyv
  • 615
  • 6
  • 26

2 Answers2

2
list_of_files = ['first_file.csv', 'second_file.csv']
for file in list_of_files:
    with open(os.path.join(path_class, file), 'a') as f:
        writer = csv.writer(f)
        writer.writerow(values)
Naszos
  • 260
  • 1
  • 10
1

You don't necessarily need the r string flag here as the string represents csv file name only. Check this answer for use of the r string flag.

Hence this code should work:

for i in range(len(list_of_file)):
    with open(os.path.join(path_class, list_of_file[i]), 'a') as f:
        writer = csv.writer(f)
        writer.writerow(values)
Shrey Shah
  • 109
  • 5