How to save file in Python

At some point, you may need to write the contents of a flat-text file from one location to another. This can be done in various ways, as shown below in our examples.

For this article, a flat-text file about Albert Einstein is saved to the current working folder. This file is called albert.txt. Contents of same below.

Albert Einstein (4 March 1879 – 18 April 1955) was a German-born theoretical physicist widely known as one of the greatest and most influential physicists of all time. Einstein is best known for developing the theory of relativity, but he also contributed significantly to developing the theory of quantum mechanics. Relativity and quantum mechanics are together the two pillars of modern physics. His mass-energy equivalence formula E = mc2, which arises from relativity theory, is called “the world’s most famous equation.”

💬 Question: How would we write code to save a flat-text file to another folder?

We can accomplish this task by one of the following options:

  • Method 1: Use absolute path
  • Method 2: Use os.path()
  • Method 3: Use shutil.copy()
  • Method 4: Use Path

Method 1: Use Absolute Path

This example uses an absolute path to save a flat-text file located in the current working folder to a different folder.

with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results)

This code starts by using a with open() statement to open two (2) flat-text files. One file is opened in read mode (try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))0) and the other in write mode (try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))1). These two (2) files save as file objects to try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))2 and try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))3, respectively.

If output to the terminal, the contents of try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))2 and try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))3 will be similar to below.

try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))6

Next, the file object try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))2 reads in the contents of the first file and saves the output to try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))8. This data is then written to the file object try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))3 and placed in the folder indicated above.

Python open() Function -- An 80/20 Guide by Example


Watch this video on YouTube

What happens if the referenced folder or file does not exist?

Add a import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)0/import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)1 statement to the code to catch and display any exception errors.

try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))

If successful, the above file should reside in the file path shown above.

Python Try Except: An Illustrated Guide


Watch this video on YouTube

Method 2: Use os.path

This example uses import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)2 to save a flat-text file located in the current working folder to a different folder.

import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)

The first line in the above code imports Python’s built-in os library. This library allows users to interact with and manipulate files and folders.

The following two (2) lines declare the folder location and the filename. These save to the variables import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)3 and import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)4, respectively.

Next, import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)5 is called and passed to the variables import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)3and import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)4. This function concatenates the file path and the filename and saves it to import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)8.

Then, the import os.path folder = 'c:\\mr_smith\\essays' file_name = 'albert.txt' file_path = os.path.join(folder, file_name) if not os.path.isdir(folder): os.mkdir(folder) with open(file_name, 'r') as fp1, \ open(file_path, 'w') as fp2: results = fp1.read() fp2.write(results)9 statement checks for the existence of the specified folder. If this folder does not exist, one is created calling import shutil current_loc = 'albert.txt' new_loc = 'c:\\mr_smith\\essays\\' + current_loc shutil.copy(current_loc, new_loc)0 and passing the folder to create as an argument.

The following section opens the two (2) files as indicated above in Method 1 and writes the contents of file 1 (try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))2) to file 2 (try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))3).

If successful, the above file should reside in the file path indicated above.

💡Note: Click here to read more about opening multiple files simultaneously.

Method 3: Use shutil.copy()

This example uses shutil.copy() from the shutil library to copy a flat-text file located in the current working folder to a different folder.

import shutil current_loc = 'albert.txt' new_loc = 'c:\\mr_smith\\essays\\' + current_loc shutil.copy(current_loc, new_loc)

The above code imports the shutil library, which offers several functions. One, in particular, allows us to copy a file from one location to another.

This code first declares the variable import shutil current_loc = 'albert.txt' new_loc = 'c:\\mr_smith\\essays\\' + current_loc shutil.copy(current_loc, new_loc)6, which contains the direct path to the file to be copied (current working folder, plus the file name).

Next, a variable import shutil current_loc = 'albert.txt' new_loc = 'c:\\mr_smith\\essays\\' + current_loc shutil.copy(current_loc, new_loc)7is declared and configured to copy the existing flat-text file to a different folder.

The final line copies the current file from the current working folder to the new location indicated above.

Method 4: Use Path

This example uses Path from the import shutil current_loc = 'albert.txt' new_loc = 'c:\\mr_smith\\essays\\' + current_loc shutil.copy(current_loc, new_loc)9 library to save a flat-text file located in the current working folder to a different folder.

from pathlib import Path with open('albert.txt', 'r') as fp1: results = fp1.read() p = Path('c:\\mr_smith\\essays\\') p.mkdir(exist_ok=True) with (p / 'albert.txt').open('w') as fp2: fp2.write(results)

The above code imports Path from the import shutil current_loc = 'albert.txt' new_loc = 'c:\\mr_smith\\essays\\' + current_loc shutil.copy(current_loc, new_loc)9 library.

The following two (2) lines open and read (try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))0) in the flat-text file located in the current working folder. The contents of this file are saved to try: with open('albert.txt', 'r') as fp1, \ open('c:\\mr_smith\\essays\\albert.txt', 'w') as fp2: results = fp1.read() fp2.write(results) except Exception as e: print('Error: ' + str(e))8.

Next, the path (or folder name) is declared where the contents of results will be written to. If this folder does not exist, it is created.

Finally, the above flat-text file is opened in write (w) mode and the contents of results is written to this file.

Summary

This article has provided four (4) ways to save a flat-text file to another folder to select the best fit for your coding requirements.

How do you create and save a file in Python?

How to Create Files in Python. In Python, you use the open() function with one of the following options – "x" or "w" – to create a new file: "x" – Create: this command will create a new file if and only if there is no file already in existence with that name or else it will return an error.

How can I save my code in Python?

Go to File and click on Save as..
In the field Save in browse for the C: drive and then select the folder PythonPrograms..
For the field File name remove everything that is there and type in Hello.py..
In the field Save as type select All Files..
Click on Save. You have just created your first Python program..

How do I save a file path in Python?

How to Save a Text File to Another Folder in Python.
Method 1: Use absolute path..
Method 2: Use os. path().
Method 3: Use shutil . copy().
Method 4: Use Path..

What is save () in Python?

The Save() function is used to save an array to a binary file in NumPy . npy format.

Postingan terbaru

LIHAT SEMUA