User12345
User12345

Reputation: 5480

Create file form python in a user specified directory

I am checking if a file is present or not if present then append to that file if not create a new file.

I have done like below.

    if os.path.exists(test + '.csv'):
        system_file = open(test + '.csv', 'a')
        pass
    else:
        system_file = open(test + '.csv', 'w')

This is checking and creating files in default location C:/users/viru/Desktop. Is there a way to create these files in C:/users/viru/testing/abc directory

Upvotes: 0

Views: 77

Answers (2)

Joe Iddon
Joe Iddon

Reputation: 20434

There is a much easier way to do this. You are correct in thinking that if the file already exists, you don't want to open it with mode 'w' as this will erase the contents. However, you can 'append' to an empty (new) file as well as a file which has already been created and has contents with the 'a' (append) mode.

So you can just do:

system_file = open(test + '.csv', 'a')

without the if-statements, as even if test is a path to a file which hasn't yet been created, you can still now write to it even though it has been opened with the append ('a') mode.

You can read more about the different modes that are accepted by the open() function here.

Hope this is of use!

Upvotes: 1

arshovon
arshovon

Reputation: 13661

You can easily achieve this using os.path.join.

I have used H:\os directory as my desired directory and shovon as my desired filename. Change it as your own input.

import os
test = os.path.join("H:",os.sep,"os","shovon")

if os.path.exists(test + '.csv'):
    system_file = open(test + '.csv', 'a')
    print("File already exists")
else:
    system_file = open(test + '.csv', 'w')
    print("New file is created")

The os.sep is used for adding separator sign based on your operating system. The path are concatenated as string and drive letter is with an extra colon as you see.

Upvotes: 0

Related Questions