ADVERTISEMENT
ADVERTISEMENT

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
    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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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

© https://www.includehelp.com some rights reserved.