Open In App

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

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

Example:




# 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

Example:




# 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:

Example:




# 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:

Example:




# 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:

Example:




# 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:

Example:




# 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


Article Tags :