How do I create a incrementing filename in Python?

后端 未结 12 2069
终归单人心
终归单人心 2020-11-28 05:45

I\'m creating a program that will create a file and save it to the directory with the filename sample.xml. Once the file is saved when i try to run the program again it over

12条回答
  •  温柔的废话
    2020-11-28 06:15

    Another solution that avoids the use of while loop is to use os.listdir() function which returns a list of all the files and directories contained in a directory whose path is taken as an argument.

    To answer the example in the question, supposing that the directory you are working in only contains "sample_i.xlm" files indexed starting at 0, you can easily obtain the next index for the new file with the following code.

    import os
    
    new_index = len(os.listdir('path_to_file_containing_only_sample_i_files'))
    new_file = open('path_to_file_containing_only_sample_i_files/sample_%s.xml' % new_index, 'w')
    

提交回复
热议问题