Write a Program to Read in a Text File and Then Write the Contents to Another File in Python
Overview
When you're working with Python, you don't need to import a library in order to read and write to a file. Information technology's handled natively in the language, albeit in a unique manner. Beneath, we outline the simple steps to read and write to a file in Python.
The first thing you'll demand to exercise is use the built-in python open file function to get a file object .
The open up function opens a file. It'southward simple. This is the first step in reading and writing files in python.
When you use the open function, information technology returns something called a file object . File objects comprise methods and attributes that tin can be used to collect information about the file yous opened. They tin can also exist used to manipulate said file.
For case, the mode attribute of a file object tells you which mode a file was opened in. And the name aspect tells y'all the name of the file.
You must empathise that a file and file object are two wholly separate – nevertheless related – things.
File Types
What you lot may know every bit a file is slightly unlike in Python.
In Windows, for instance, a file tin can exist any detail manipulated, edited or created by the user/OS. That means files can exist images, text documents, executables, and excel file and much more. Most files are organized past keeping them in private folders.
A file In Python is categorized as either text or binary, and the difference betwixt the two file types is important.
Text files are structured every bit a sequence of lines, where each line includes a sequence of characters. This is what y'all know equally lawmaking or syntax.
Each line is terminated with a special character, chosen the EOL or Stop of Line character. There are several types, but the most common is the comma {,} or newline character. Information technology ends the electric current line and tells the interpreter a new ane has begun.
A backslash character can too be used, and it tells the interpreter that the next character – following the slash – should be treated every bit a new line. This character is useful when you don't want to start a new line in the text itself but in the code.
A binary file is whatever type of file that is not a text file. Because of their nature, binary files can but exist candy by an awarding that know or understand the file's construction. In other words, they must be applications that can read and translate binary.
Reading Files in Python
In Python, files are read using the open up() method. This is one of Python'south congenital-in methods, made for opening files.
The open() function takes two arguments: a filename and a file opening mode. The filename points to the path of the file on your computer, while the file opening manner is used to tell the open up() part how we plan to interact with the file.
By default, the file opening mode is set to read-but, meaning we'll only have permission to open and examine the contents of the file.
On my computer is a binder called PythonForBeginners. In that binder are three files. I is a text file named emily_dickinson.txt, and the other two are python files: read.py and write.py.
The text file contains the following poem, written past poet Emily Dickinson. Perhaps we are working on a verse program and have our poems stored as files on the computer.
Success is counted sweetest
Past those who ne'er succeed.
To comprehend a nectar
Requires sorest demand.
Not one of all the Purple Host
Who took the Flag today
Tin tell the definition
And so articulate of Victory
As he defeated, dying
On whose forbidden ear
The distant strains of triumph
Burst agonized and articulate.
Before we can do anything with the contents of the poem file, we'll need to tell Python to open it. The file read.py, contains all the python lawmaking necessary to read the poem.
Any text editor can be used to write the lawmaking. I'm using the Atom code editor, which is my editor of pick for working in python.

# read.py # loading a file with open up() myfile = open("emily_dickinson.txt") # reading each line of the file and press to the console for line in myfile: print(line)
I've used Python comments to explain each pace in the code. Follow this link to learn more virtually what a Python annotate is.
The example above illustrates how using a uncomplicated loop in Python can read the contents of a file.
When it comes to reading files, Python takes care of the heaving lifting behind the scenes. Run the script past navigating to the file using the Control Prompt — or Terminal — and typing 'python' followed by the name of the file.
Windows Users: Before you tin can use the python keyword in your Command Prompt, you'll need to prepare the surround variables. This should accept happened automatically when you installed Python, just in case it didn't, y'all may demand to do it manually.
>python read.py

Information provided by the open() method is ordinarily stored in a new variable. In this case, the contents of the poem are stored in the variable "myfile."
Once the file is created, we tin can use a for loop to read every line in the file and impress its contents to the command line.
This is a very simple example of how to open up a file in Python, but student's should be aware that the open() method is quite powerful. For some projects information technology will be the only matter needed to read and write files with Python.
Writing Files in Python
Earlier we tin write to a file in Python, information technology must start be opened in a different file opening mode. We can do this by supplying the open up() method with a special statement.
In Python, write to file using the open() method. You'll need to laissez passer both a filename and a special character that tells Python nosotros intend to write to the file.
Add the following code to write.py. We'll tell Python to look for a file named "sample.txt" and overwrite its contents with a new message.
# open the file in write way myfile = open("sample.txt",'w') myfile.write("Hello from Python!")
Passing 'w' to the open up() method tells Python to open up the file in write mode. In this mode, any data already in the file is lost when the new data is written.
If the file doesn't be, Python will create a new file. In this case, a new file named "sample.txt" will be created when the program runs.
Run the program using the Control Prompt:
>python write.py
Python tin can also write multiple lines to a file. The easiest manner to practise this is with the writelines() method.
# open the file in write mode myfile = open("sample.txt",'westward') myfile.writelines("Hello Earth!","We're learning Python!") # shut the file myfile.shut()
Nosotros can also write multiple lines to a file using special characters:
# open the file in write manner myfile = open("verse form.txt", 'w') line1 = "Roses are red.\n" line2 = "Violets are blue.\n" line3 = "Python is great.\n" line4 = "Then are you.\n" myfile.write(line1 + line2 + line3 + line4)
Using cord concatenation makes it possible for Python to salve text data in a variety of ways.
However, if we wanted to avert overwriting the information in a file, and instead append information technology or change it, we'd have to open the file using another file opening style.
File Opening Modes
Past default, Python will open the file in read-only mode. If nosotros want to do annihilation other than just read a file, we'll demand to manually tell Python what nosotros intend to do with information technology.
- 'r' – Read Manner: This is the default mode for open up() . The file is opened and a pointer is positioned at the beginning of the file'southward content.
- 'west' – Write Mode: Using this mode will overwrite any existing content in a file. If the given file does not be, a new one will be created.
- 'r+' – Read/Write Style: Use this fashion if you need to simultaneously read and write to a file.
- 'a' – Append Mode: With this mode the user tin can suspend the information without overwriting any already existing information in the file.
- 'a+' – Append and Read Mode: In this manner you can read and suspend the data without overwriting the original file.
- '10' – Exclusive Creating Mode: This way is for the sole purpose of creating new files. Use this way if you know the file to exist written doesn't exist beforehand.
Note: These examples assume the user is working with text file types. If the intention is to read or write to a binary file type, an additional argument must be passed to the open() method: the 'b' graphic symbol.
# binary files demand a special argument: 'b' binary_file = open up("song_data.mp3",'rb') song_data = binary_file.read() # close the file binary_file.close()
Closing Files with Python
Subsequently opening a file in Python, it's of import to close it afterward you're done with information technology. Closing a file ensures that the program can no longer access its contents.
Close a file with the close() method.
# open a file myfile = open("verse form.txt") # an array to shop the contents of the file lines = [] For line in myfile: lines.append(line) # shut the file myfile.close() For line in liens: print(line)
Opening Other File Types
The open() method tin read and write many different file types. Nosotros've seen how to open binary files and text files. Python tin can also open images, allowing y'all to view and edit their pixel data.
Before Python tin open an image file, the Pillow library (Python Imaging Library) must be installed. Information technology's easiest to install this module using pip.
pip install Pillow
With Pillow installed, Python can open image files and read their contents.
From PIL import Prototype # tell Pillow to open the paradigm file img = Image.open("your_image_file.jpg") img.show() img.shut()
The Pillow library includes powerful tools for editing images. This has made it one of the well-nigh popular Python libraries.
With Statement
You lot tin can also piece of work with file objects using the with argument. It is designed to provide much cleaner syntax and exceptions handling when you are working with code. That explains why it'southward expert practice to use the with statement where applicable.
One bonus of using this method is that any files opened will be closed automatically subsequently you lot are washed. This leaves less to worry almost during cleanup.
To employ the with statement to open up a file:
with open("filename") as file:
At present that you lot empathise how to phone call this argument, let's accept a look at a few examples.
with open up("poem.txt") as file: data = file.read() practice something with data
You can too telephone call upon other methods while using this argument. For instance, you tin can exercise something like loop over a file object:
with open("verse form.txt") every bit f: for line in f: impress line,
You'll also notice that in the above example we didn't utilise the " file.close() " method considering the with argument will automatically telephone call that for us upon execution. It really makes things a lot easier, doesn't it?
Splitting Lines in a Text File
As a final case, let's explore a unique part that allows y'all to split the lines taken from a text file. What this is designed to do, is split the cord contained in variable information whenever the interpreter encounters a space grapheme.
But just because we are going to use it to carve up lines after a infinite graphic symbol, doesn't mean that'southward the just way. Y'all tin can really dissever your text using whatever character you wish – such as a colon, for case.
The lawmaking to do this (also using a with argument) is:
with open up( " hello.text ", "r") as f: data = f.readlines () for line in data: words = line.split () print words
If y'all wanted to use a colon instead of a space to split your text, you lot would simply change line.split() to line.split(":").
The output for this will exist:
["hi", "world", "how", "are", "you", "today?"] ["today", "is", "Saturday"]
The reason the words are presented in this way is because they are stored – and returned – as an array. Exist sure to remember this when working with the split function.
Decision
Reading and writing files in Python involves an understanding of the open up() method. By taking advantage of this method's versatility, information technology's possible to read, write, and create files in Python.
Files Python can either be text files or binary files. It'southward too possible to open and edit prototype information using the Pillow module.
Once a file'south information is loaded in Python, there's virtually no end to what tin be washed with information technology. Programmers often work with a large number of files, using programs to generate them automatically.
As with any lesson, there is merely so much that can be covered in the space provided. Hopefully you've learned enough to become started reading and writing files in Python.
More Reading
Official Python Documentation – Reading and Writing Files
Python File Treatment Cheat Sail
Recommended Python Training
Course: Python 3 For Beginners
Over fifteen hours of video content with guided instruction for beginners. Acquire how to create existent world applications and master the nuts.
Source: https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
0 Response to "Write a Program to Read in a Text File and Then Write the Contents to Another File in Python"
Post a Comment