Python how to concatenate file names, create and verify folder?

In the example below you can see how to create a new file in Python with:

  • verifying if folder exists - otherwise create all folders
    • predefined path
    • current working folder
  • concatenate file names with trailing slash and taking care for the OS
  • create file with different extensions:
    • CSV
    • JSON
    • text
  • create new file in write mode
import os

file_name =' myfile' # file name
path = os.path.dirname('/home/user/') # predefined folder
curr_path = os.getcwd() # get working folder

# work with several extensions
csv_file = os.path.join(path, file_name + '.csv')
txt_file = os.path.join(path, file_name + '.txt')

# check if folder exists otherwise create it
if not os.path.exists(path):
    os.makedirs(path)

# create new file and write inside
with open(csv_file, 'w+') as csv:
    for msg in ['a', 'b', 'c', 'd', 'e']:
        csv.write(msg + '\n')

with open(txt_file, 'w+') as csv:
    for msg in range(1, 5):
        csv.write(str(msg) + '\n')

Related Article