1

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
1
  • Not sure about the excel part, but try '/home/exx/Documents/Input/%d/2.mp4' % (i) or f'/home/exx/Documents/Input/{i}/2.mp4' for the path string part. EDIT: To make it more clear, remove the comma before % (i). Commented Oct 5, 2021 at 17:34

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

Comments

1

This also works.

import xlsxwriter

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

#column parameter is set to zero (0), because you want all the entries to be on the first column
for i in range(4):
    worksheet.write(i, 0,  f'/home/exx/Documents/Input/{i}/2.mp4')

workbook.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.