How to save file with file name from user using Python?

13 Jan, 2021
Prerequisites:
File Handling in Python
Reading and Writing to text files in Python
Saving a file with the user’s custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a copy of a file(Save As). Let’s discuss these in detail.  
Method 1: Using open() function
We can create a new file using the open() function with one of the access modes listed below.  
Syntax:  
open( filepath , mode )
Access modes:
Write Only (‘w’): Creates a new file for writing, if the file doesn’t exist otherwise truncates and over-write existing file.
Write and Read (‘w+’): Creates a new file for reading & writing, if the file doesn’t exist otherwise truncates and over-write existing file.
Append Only (‘a’): Creates a new file for writing, if the file doesn’t exist otherwise data being written will be inserted at the end of the file.
Append and Read (‘a+’): Creates a new file for reading & writing, if the file doesn’t exist otherwise data being written will be inserted at the end of the file.
Approach
Get file name from the user
Open a file with mentioned access mode
Create this file with the entered name
Example:
Python3
# path of this scriptdirectory = "D:\gfg\\"  # get fileName from userfilepath = directory + input("Enter filename: ")  # Creates a new filewith open(filepath, 'w+') as fp:    pass
Output:
Enter filename: newgfgfile.txt
Method 2: Using pathlib library
pathlib offers a set of classes to handle filesystem paths. We can use touch() method to create the file at a given path it updates the file modification time with the current time and marks exist_ok as True, otherwise, FileExistsError is raised.
Syntax: 
Path.touch(mode=0o666, exist_ok=True)
Approach
Import module
Get file name from the user
Create a file with the entered name
Example:
Python3
# import pathlib moduleimport pathlib  # path of this scriptdirectory = "D:\gfg\\"  # get fileName from userfilepath = directory + input("Enter filename:")  # To create a filepathlib.Path(filepath).touch()
Output:
Enter filename:gfgfile2.txt
Method 1: Using the os module
Python’s OS module includes functions to communicate with the operating system. Here, we can use rename() method to save a file with the name specified by the user.
Syntax: 
rename(src, dest, *, src_dir_fd=None, dst_dir_fd=None)
Approach:
Import module
Get source file name
Get destination file name
Rename the source file to destination file or directory
If destination file already exists, the operation will fail with an OSError.
Example:
Python3
# import os libraryimport os  # get source file namesrc = input("Enter src filename:")  # get destination file namedest = input("Enter dest filename:")  # rename source file name with destination file nameos.rename(src, dest)
Output:
Enter src filename:D:\gfg\newgfgfile.txt 
Enter dest filename:D:\gfg\renamedfile1.txt
Method 2: Using pathlib library
pathlib also provides rename() function to change the name of a file which more or less serves the same purpose as given above. 
syntax:
 Path(filepath).rename(target) 
Approach:
Import module
Get source file name
Get destination file name
Rename source file or directory to the destination specified
Return a new instance of the Path to the destination. (On Unix, if the target exists and the user has permission, it will be replaced.)
Example:
Python3
# import pathlib moduleimport pathlib  # get source file namesrc = input("Enter src filename:")  # get destination file nametarget = input("Enter target filename:")  # rename source file name with target file namepathlib.Path(src).rename(target)
Output:
Enter src filename:D:\gfg\gfgfile2.txt 
Enter target filename:D:\gfg\renamedfile2.txt
Method 1: Using the os module 
We can use popen() method to make a copy of the source file to the target file with the name specified by the user.
Syntax:
 popen( command, mode , buffersize )
os.popen() get command to be performed as the first argument, access mode as the second argument which can be read (‘r’) or write (‘w’) and finally buffer size. The default mode is read and 0 for no buffering, positive integers for buffer size.
Approach:
Import module
Get source file name
Get destination file name
Copy source to destination
Example:
Python
# import os moduleimport os  # get source file namesrc = input("Enter src filename:")  # get destination file namedestination = input("Enter target filename:")  # copies source to destination fileos.popen(f"copy {src} {destination}")
Output:
Enter src filename:D:\gfg\renamedfile1.txt 
Enter target filename:D:\gfg\copied-renamedfile1.txt
Method 2: Using the shutil module
The shutil module offers several high-level operations on files and collections of files. Its copyfile() method is used to rename the file with the user preferred name.
Syntax: 
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
Approach:
Import module
Get source file name
Get destination file name
Copy source file to a new destination file. If both file names specify the same file, SameFileError is raised and if destination file already exists, it will be replaced.
Example:
Python3
# import shutil moduleimport shutil  # get source file namesrc = input("Enter src filename:")  # get destination file namedest = input("Enter target filename:")  # copies source file to a new destination fileshutil.copyfile(src, dest)
Output:
Enter src filename:D:\gfg\renamedfile2.txt 
Enter target filename:D:\gfg\copied-renamedfile2.txt
Picked
Python file-handling-programs
python-file-handling
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.