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:
Changing directory using chdir() method and passing relative path to the file (path from the current directory to that 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 program to create a new file in another directory
Output:
File : demo.txt
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.
need an explanation for this answer? contact us directly to get an explanation for this answer