Skip to content
Advertisement

How to generate multiple file paths and save them into a excel with python

I want to generate hundreds of file paths in python and save them into an excel file. Each path should save in a separate row and paths vary just by one value. I am not sure how to iterate it through a for loop.

Here is my try:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

for i in range (4):
    worksheet.write('A%d', '/home/exx/Documents/Input/%d/2.mp4', %(i)))  
    workbook.close()

Output is excel file should be like below:

/home/exx/Documents/Input/0/2.mp4
/home/exx/Documents/Input/1/2.mp4
/home/exx/Documents/Input/2/2.mp4
/home/exx/Documents/Input/3/2.mp4

Advertisement

Answer

There are a few mistakes here:

  • workbook should be closed outside of the for loop
  • if you want to start generation from 0 but write the first line in row number one in the excel file you should do i+1 in the row count
  • there shouldn’t be a space after a range keyword

The fixed snipped should look like this:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

for i in range(4):
    worksheet.write(f'A{i+1}', f'/home/exx/Documents/Input/{i}/2.mp4')

workbook.close()
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement