Python Forum
Creating a file with variable name but distinct extension
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a file with variable name but distinct extension
#1
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
Reply
#2
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Creating/Moving file DeadlyKnight 3 1,512 Mar-25-2022, 06:25 PM
Last Post: ibreeden
  creating dict out of CSV file without the headers ranbarr 6 2,648 May-09-2021, 08:26 PM
Last Post: ranbarr
  Creating Disassembler for a bin file(total beginner) SoulsKeeper 1 2,461 Sep-04-2018, 04:15 PM
Last Post: Larz60+
  Creating a variable that displays time groovydingo 3 2,914 Apr-17-2018, 04:46 AM
Last Post: tannishpage

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020