Python program to 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.
Submitted by Shivang Yadav, on March 17, 2021

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

    # Changing current path to the directory

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

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


Current Directory : /home/pythonFiles

File : demo.txt

This is demo File


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!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.