How to save file with file name from user using Python?
Last Updated :
13 Jan, 2021
Prerequisites:
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. Â
Creating a new file
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 script
directory = "D:\gfg\\"
# get fileName from user
filepath = directory + input("Enter filename: ")
# Creates a new file
with 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 module
import pathlib
# path of this script
directory = "D:\gfg\\"
# get fileName from user
filepath = directory + input("Enter filename:")
# To create a file
pathlib.Path(filepath).touch()
Output:
Enter filename:gfgfile2.txt

Renaming a file
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 library
import os
# get source file name
src = input("Enter src filename:")
# get destination file name
dest = input("Enter dest filename:")
# rename source file name with destination file name
os.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 module
import pathlib
# get source file name
src = input("Enter src filename:")
# get destination file name
target = input("Enter target filename:")
# rename source file name with target file name
pathlib.Path(src).rename(target)
Output:
Enter src filename:D:\gfg\gfgfile2.txt
Â
Enter target filename:D:\gfg\renamedfile2.txt

Copying or duplicating a file
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 module
import os
# get source file name
src = input("Enter src filename:")
# get destination file name
destination = input("Enter target filename:")
# copies source to destination file
os.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 module
import shutil
# get source file name
src = input("Enter src filename:")
# get destination file name
dest = input("Enter target filename:")
# copies source file to a new destination file
shutil.copyfile(src, dest)
Output:
Enter src filename:D:\gfg\renamedfile2.txt
Â
Enter target filename:D:\gfg\copied-renamedfile2.txt
Similar Reads
How to Download Files from Urls With Python
Here, we have a task to download files from URLs with Python. In this article, we will see how to download files from URLs using some generally used methods in Python. Download Files from URLs with PythonBelow are the methods to Download files from URLs with Python: Using 'requests' ModuleUsing 'url
2 min read
How to open a file using the with statement
The with keyword in Python is used as a context manager. As in any programming language, the usage of resources like file operations or database connections is very common. But these resources are limited in supply. Therefore, the main problem lies in making sure to release these resources after usa
4 min read
Save Image To File in Python using Tkinter
Saving an uploaded image to a local directory using Tkinter combines the graphical user interface capabilities of Tkinter with the functionality of handling and storing images in Python. In this article, we will explore the steps involved in achieving this task, leveraging Tkinter's GUI features to
4 min read
How to read multiple text files from folder in Python?
Prerequisite: File Handlingos Python is a strong language which is extremely capable even when it comes to file handling. In this article, we will learn how to read multiple text files from a folder using python. Approach: Import modulesAdd path of the folderChange directoryGet the list of a file fr
2 min read
How to Download and Upload Files in FTP Server using Python?
Prerequisite: FTP, ftplib Here, we will learn how to Download and Upload Files in FTP Server Using Python. Before we get started, first we will understand what is FTP. FTP(File Transfer Protocol) File Transfer Protocol(FTP) is an application layer protocol that moves files between local and remote f
3 min read
How to Delete files in Python using send2trash module?
In this article, we will see how to safely delete files and folders using the send2trash module in Python. Using send2trash, we can send files to the Trash or Recycle Bin instead of permanently deleting them. The OS module's unlink(), remove() and rmdir() functions can be used to delete files or fol
2 min read
How to open multiple files using "with open" in Python?
Python has various highly useful methods for working with file-like objects, like the with feature. But what if we need to open several files in this manner? You wouldn't exactly be "clean" if you had a number of nested open statements. In this article, we will demonstrate how to open multiple files
2 min read
How To Upload And Download Files From AWS S3 Using Python?
Pre-requisite: AWS and S3Amazon Web Services (AWS) offers on-demand cloud services which means it only charges on the services we use (pay-as-you-go pricing). AWS S3 is a cloud storage service from AWS. S3 stands for 'Simple Storage Service. It is scalable, cost-effective, simple, and secure. We gen
3 min read
How to print all files within a directory using Python?
The OS module is one of the most popular Python modules for automating the systems calls and operations of an operating system. With a rich set of methods and an easy-to-use API, the OS module is one of the standard packages and comes pre-installed with Python. In this article, we will learn how to
3 min read
How To Send Files Using Python Built-In Http Server
Python's built-in HTTP server offers a straightforward way to share files over a local network or the internet without the need for complex setups. In this tutorial, we'll walk through the step-by-step process of using Python's built-in HTTP server to send files to clients. Setting Up the HTTP Serve
2 min read