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 fp1
and fp2
, respectively.
If output to the terminal, the contents of fp1
and fp2
will be similar to below.
<_io.TextIOWrapper name='einstein.txt' mode='r' encoding='cp1252'> |
Next, the file object fp1
reads in the contents of the first file and saves the output to results
. This data is then written to the file object fp2
and placed in the folder indicated above.
What happens if the referenced folder or file does not exist?
Add a try
/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 folder
and file_name
, respectively.
Next, os.path.join()
is called and passed to the variables folder
and file_name
. This function concatenates the file path and the filename and saves it to file_path
.
Then, the if
statement checks for the existence of the specified folder. If this folder does not exist, one is created calling os.mkdir()
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 (fp1
) to file 2 (fp2
).
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 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
This example uses Path
from the pathlib
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 pathlib
library.
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 results
.
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.
Good Luck & Happy Coding!
Programming Humor
