Problem Formulation and Solution Overview
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.”
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 (
r) and the other in write mode (
w). These two (2) files save as file objects to
If output to the terminal, the contents of
fp2 will be similar to below.
What happens if the referenced folder or file does not exist?
except 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.
Method 2: Use os.path
This example uses
os.path 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
os.path.join() is called and passed to the variables
file_name. This function concatenates the file path and the filename and saves it to
The following section opens the two (2) files as indicated above in Method 1 and writes the contents of file 1 (
fp1) to file 2 (
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()
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
current_loc, which contains the direct path to the file to be copied (current working folder, plus the file name).
Next, a variable
new_loc is 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
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 following two (2) lines open and read (
r) in the flat-text file located in the current working folder. The contents of this file are saved to
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.
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.
Good Luck & Happy Coding!
At university, I found my love of writing and coding. Both of which I was able to use in my career.
During the past 15 years, I have held a number of positions such as:
In-house Corporate Technical Writer for various software programs such as Navision and Microsoft CRM
Corporate Trainer (staff of 30+)
Implementation Specialist for Navision and Microsoft CRM
Senior PHP Coder