Open In App

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

Last Updated : 13 Jan, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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



Next Article

Similar Reads

NumPy save() Method | Save Array to a File
The NumPy save() method is used to store the input array in a binary file with the 'npy extension' (.npy). Example: C/C++ Code import numpy as np a = np.arange(5) np.save('array_file', a) SyntaxSyntax: numpy.save(file, arr, allow_pickle=True, fix_imports=True) Parameters: file: File or filename to which the data is saved. If the file is a string or
2 min read
Save user input to a Excel File in Python
In this article, we will learn how to store user input in an excel sheet using Python, What is Excel? Excel is a spreadsheet in a computer application that is designed to add, display, analyze, organize, and manipulate data arranged in rows and columns. It is the most popular application for accounting, analytics, data presentation, etc. Methods us
4 min read
Python PIL save file with datetime as name
In this article, we are going to see how to save image files with datetime as a name using PIL Python. Modules required: PIL: This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities. pip install Pillow datetime: This module helps us to work with dates and times in
2 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read
Save multiple matplotlib figures in single PDF file using Python
In this article, we will discuss how to save multiple matplotlib figures in a single PDF file using Python. We can use the PdfPages class's savefig() method to save multiple plots in a single pdf. Matplotlib plots can simply be saved as PDF files with the .pdf extension. This saves Matplotlib-generated figures in a single PDF file named Save multip
3 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 enhance the user experience in image management ap
4 min read
GUI application to search a country name from a given state or city name using Python
In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so l
2 min read
How To Save The Network In XML File Using PyBrain
In this article, we are going to see how to save the network in an XML file using PyBrain in Python. A network consists of several modules. These modules are generally connected with connections. PyBrain provides programmers with the support of neural networks. A network can be interpreted as an acyclic directed graph where each module serves the p
2 min read
How to Save a Plot to a File Using Matplotlib?
Matplotlib is a widely used Python library to plot graphs, plots, charts, etc. show() method is used to display graphs as output, but don’t save it in any file. In this article, we will see how to save a Matplotlib plot as an image file. Save a plot in MatplotlibBelow are the ways by which we can save a plot to a file using Matplotlib in Python: Us
3 min read
How to save a Python Dictionary to a CSV File?
Prerequisites: Working with csv files in Python CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same. Import cs
2 min read
How to Save Seaborn Plot to a File in Python?
Seaborn provides a way to store the final output in different desired file formats like .png, .pdf, .tiff, .eps, etc. Let us see how to save the output graph to a specific file format. Saving a Seaborn Plot to a File in Python Import the inbuilt penguins dataset from seaborn package using the inbuilt function load_dataset. C/C++ Code # Import the s
2 min read
Save a image file on a Postgres database - Python
In this article, we are going to see how to save image files on a postgresql database using Python. Psycopg2 is a driver, that is used, for interacting, with Postgres data, using the Python scripting language. It is, used to perform, CRUD operations on Postgres data. Data handled in applications can be in any format. For example, Strings, Numbers,
4 min read
Python Tweepy - Getting the screen name of a user
In this article we will see how we can get the screen name of a user. Screen name is the username of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their screen name, often in a shortened version. All the screen names must be unique. Ident
2 min read
Python Tweepy - Getting the name of a user
In this article we will see how we can get the name of a user. Name is the display name of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their display name. Unlike screen names, the names need not be unique. Moreover the names can be in a
2 min read
Python | Print the initials of a name with last name in full
Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots. Examples: Input : geeks for geeks Output : G.F.Geeks Input : mohandas karamchand gandhi Output : M.K.Gandhi A naive approach of this will be to iterate for spaces and print the next letter after every space excep
3 min read
Python IMDbPY – Getting Person name from searched name
In this article we will see how we can get the person name from the searched list of name, we use search_name method to find all the related names.search_name method returns list and each element of list work as a dictionary i.e. they can be queried by giving the key of the data, here key will be name. Syntax : names[0]['name']Here names is the lis
2 min read
Save a dictionary to a file
A dictionary in Python is a collection where every value is mapped to a key. They are unordered, mutable and there is no constraint on the data type of values and keys stored in the dictionary. This makes it tricky for dictionaries to be stored as files. Know more about dictionaries here. Syntax: dictionary = {'geek': 1, 'supergeek': True, 4: 'geek
2 min read
How to save a NumPy array to a text file?
Let us see how to save a numpy array to a text file. Method 1: Using File handling Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function. Below are some programs of the this approach: Example 1: C
3 min read
How to Save Pandas Dataframe as gzip/zip File?
Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users. Converting to z
2 min read
How to extract paragraph from a website and save it as a text file?
Perquisites: Beautiful soupUrllib Scraping is an essential technique which helps us to retrieve useful data from a URL or a html file that can be used in another manner. The given article shows how to extract paragraph from a URL and save it as a text file. Modules Needed bs4: Beautiful Soup(bs4) is a Python library used for getting data from HTML
2 min read
How to save pyttsx3 results to MP3 or WAV file?
In this article, we will see how to generate and save pyttsx3 results as mp3 and wav file. Pyttsx3 is a python module that provides a Text to Speech API. We can use this API to convert the text into voice. Environment setup: To use pyttsx3 we have to install espeak and ffmpeg first. sudo apt update sudo apt install espeak sudo apt install ffmpeg Ad
3 min read
Django - How to Create a File and Save It to a Model's FileField?
Django is a very powerful web framework; the biggest part of its simplification for building web applications is its built-in feature of handling file uploads with FileField. Images, documents, or any other file types, Django's FileField makes uploading files through our models easy. In this article, we will learn how to create a file and save it i
5 min read
Pafy - Getting User Name of the Uploader
In this article we will see how we can get the username of the given youtube video's uploader in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Username is the handler unique name used by the person to upload the given video on you
2 min read
How to create a bar chart and save in pptx using Python?
World Wide Web holds large amounts of data available that is consistently growing both in quantity and to a fine form. Python API allows us to collect data/information of interest from the World Wide Web. API is a very useful tool for data scientists, web developers, and even any casual person who wants to find and extract information programmatica
10 min read
Save image properties to CSV using Python
In this article, we are going to write python scripts to find the height, width, no. of channels in a given image file and save it into CSV format. Below is the implementation for the same using Python3. The prerequisite of this topic is that you have already installed NumPy and OpenCV. Approach: First, we will load the required libraries into the
3 min read
Extract Video Frames from Webcam and Save to Images using Python
There are two libraries you can use: OpenCV and ImageIO. Which one to choose is situation-dependent and it is usually best to use the one you are already more familiar with. If you are new to both then ImageIO is easier to learn, so it could be a good starting point. Whichever one you choose, you can find examples for both below: ImageIOInstallatio
2 min read
Save Matplotlib Figure as SVG and PDF using Python
In this article, we will see how can we save the Matplotlib figure as Scalable Vector Graphics(SVG) using Python or any other file format for further use. The required modules for this tutorial are Matplotlib. Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. If you had not installed the
3 min read
Save API data into CSV format using Python
In this article, we are going to see how can we fetch data from API and make a CSV file of it, and then we can perform various stuff on it like applying machine learning model data analysis, etc. Sometimes we want to fetch data from our Database Api and train our machine learning model and it was very real-time by applying this method we can train
6 min read
How to save and load cookies in Selenium using Python
In web automation and testing, maintaining session information across different runs of scripts is often necessary. Cookies are a great way to save session data to avoid logging in repeatedly. Selenium, a popular tool for web testing, provides straightforward ways to save and load cookies using Python. In this article, we will learn all the steps t
4 min read
MoviePy – Getting Original File Name of Video File Clip
In this article we will see how we can get the original file name of the video file in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Original file name is the name of the original video that existed in the first place i.e which was loaded, even after altering and editing of the vi
2 min read
  翻译: