Python program to create a new file in another directory

Python | Create a new file in another directory: Here, we will write a Python program to create a new file in another directory which we will create in the current directory. By Shivang Yadav Last updated : July 05, 2023

Python programming language allows programmers to change, create and delete files and directories in programs. Using these concepts, we can create a new file in another directory by following these two easy steps:

  1. Changing directory using chdir() method and passing relative path to the file (path from the current directory to that directory).
  2. Create the new file in this directory.

Python program to create a new file in another directory

# importing os library
import os

def main():
    # creating a new directory
    os.mkdir("pythonFiles")

    # Changing current path to the directory
    os.chdir("pythonFiles")

    # creating a new file for writing operation
    fo = open("demo.txt","w")
    fo.write("This is demo File")
    fo.close()

    # printing the current file directory
    print("Current Directory :",os.getcwd())
    
if __name__=="__main__":main()

Output

Current Directory : /home/pythonFiles

File : demo.txt

This is demo File

Explanation

In the above code, we have created a new directory "pythonFile" , then changed the directory to "pythonFile". In this directory we have created our file "demo.txt" in which we have written some text and then printed the current file directory.

Python file handling programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.