Python Forum
Creating a file with variable name but distinct extension - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Creating a file with variable name but distinct extension (/thread-6546.html)



Creating a file with variable name but distinct extension - Moeniac - Nov-27-2017

Hello everybody,
for my current homework i need to create an amount of *.csv files, however the filename must be taken from a list that is provided as a *.txt-document .
i succesfully wrote a code that takes the right string out of the provided *txt, i fail to write the code correctly so it adds the file extension. Angry


right now it looks like this

"with open(namefromtxt,".csv","w")as csv:"

thanks in advance from germany

Moeniac


RE: Creating a file with variable name but distinct extension - DeaD_EyE - Nov-27-2017

Example:

file_list_without_extension = ['foo', 'bar', 'baz']

for filename in file_list_without_extension:
    with open(filename + '.csv', 'w') as csv_file:
        # code
        pass
Or you can prepare the list before:

file_list_without_extension = ['foo', 'bar', 'baz']
file_list_with_extension = [name + '.csv' for name in file_list_without_extension]
If you have a bunch of csv-files and want to access them with a wild card, you can use glob.
glob.glob('*.csv') # returns a list of .csv files of the current working directory