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

Published on Aug. 22, 2023, 12:15 p.m.

To save a file in Python with a file name specified by the user, you can use the input() function to ask the user for the file name, and then use that file name when opening the file for writing. Here’s an example:

filename = input("Enter file name: ")

with open(filename, 'w') as file:
    file.write("Hello, world!")

In this example, the input() function is used to get the file name from the user, and then the with statement is used to open the file for writing. The write() method is used to write the string “Hello, world!” to the file.

You can of course replace “Hello, world!” with whatever data you would like to save. Just make sure to handle exceptions that may occur during file operations, and also note that the user must have permission to create and write to the specified file.

Tags:

related content