Python Open a File for Reading and Writing
Overview
When you lot're working with Python, yous don't need to import a library in order to read and write to a file. It'southward handled natively in the language, albeit in a unique style. Below, we outline the simple steps to read and write to a file in Python.
The first affair you'll need to practice is use the congenital-in python open up file role to get a file object .
The open part opens a file. It'southward unproblematic. This is the showtime step in reading and writing files in python.
When you employ the open part, information technology returns something called a file object . File objects contain methods and attributes that tin be used to collect information nearly the file you opened. They can also be used to manipulate said file.
For example, the manner attribute of a file object tells you lot which mode a file was opened in. And the name attribute tells you lot the proper noun of the file.
You must understand that a file and file object are two wholly split up – yet related – things.
File Types
What you may know as a file is slightly different in Python.
In Windows, for instance, a file can exist any item manipulated, edited or created by the user/Os. That means files tin be images, text documents, executables, and excel file and much more. Most files are organized by keeping them in private folders.
A file In Python is categorized every bit either text or binary, and the difference between the two file types is important.
Text files are structured as a sequence of lines, where each line includes a sequence of characters. This is what y'all know as code or syntax.
Each line is terminated with a special graphic symbol, called the EOL or End of Line character. There are several types, simply the virtually common is the comma {,} or newline grapheme. It ends the current line and tells the interpreter a new i has begun.
A backslash graphic symbol tin can also be used, and it tells the interpreter that the next grapheme – following the slash – should be treated every bit a new line. This graphic symbol is useful when you lot don't want to outset a new line in the text itself but in the code.
A binary file is any type of file that is not a text file. Because of their nature, binary files can just be processed by an application that know or empathise the file's structure. In other words, they must exist applications that can read and translate binary.
Reading Files in Python
In Python, files are read using the open() method. This is one of Python's congenital-in methods, made for opening files.
The open() part 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 mode is used to tell the open() function how we plan to interact with the file.
By default, the file opening mode is set to read-simply, meaning we'll only have permission to open up and examine the contents of the file.
On my reckoner 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 verse form, written past poet Emily Dickinson. Perhaps we are working on a poetry program and have our poems stored as files on the figurer.
Success is counted sweetest
By those who ne'er succeed.
To encompass a nectar
Requires sorest demand.
Not one of all the Purple Host
Who took the Flag today
Can tell the definition
So clear of Victory
As he defeated, dying
On whose forbidden ear
The distant strains of triumph
Burst aching and clear.
Before we tin do anything with the contents of the verse form file, nosotros'll need to tell Python to open up it. The file read.py, contains all the python code necessary to read the poem.
Any text editor can be used to write the code. I'm using the Atom lawmaking editor, which is my editor of choice for working in python.
# read.py # loading a file with open() myfile = open("emily_dickinson.txt") # reading each line of the file and printing to the console for line in myfile: print(line)
I've used Python comments to explicate each step in the code. Follow this link to learn more virtually what a Python annotate is.
The example above illustrates how using a simple loop in Python can read the contents of a file.
When information technology comes to reading files, Python takes intendance of the heaving lifting behind the scenes. Run the script by navigating to the file using the Command Prompt — or Concluding — and typing 'python' followed by the proper noun of the file.
Windows Users: Before you lot tin can employ the python keyword in your Command Prompt, you'll demand to fix the surround variables. This should accept happened automatically when you lot installed Python, but in case it didn't, you may need to do information technology manually.
>python read.py
Data provided past the open() method is usually stored in a new variable. In this example, the contents of the poem are stored in the variable "myfile."
Once the file is created, we tin use a for loop to read every line in the file and print its contents to the command line.
This is a very uncomplicated case of how to open a file in Python, but pupil's should exist aware that the open() method is quite powerful. For some projects it will be the but thing needed to read and write files with Python.
Writing Files in Python
Earlier we can write to a file in Python, it must first be opened in a unlike file opening mode. We can do this by supplying the open() method with a special statement.
In Python, write to file using the open up() method. You lot'll demand to pass both a filename and a special graphic symbol that tells Python nosotros intend to write to the file.
Add together 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 fashion myfile = open("sample.txt",'due west') myfile.write("Hello from Python!")
Passing 'w' to the open() method tells Python to open the file in write style. In this style, whatsoever information already in the file is lost when the new data is written.
If the file doesn't exist, Python will create a new file. In this example, a new file named "sample.txt" will be created when the plan runs.
Run the programme using the Command Prompt:
>python write.py
Python can also write multiple lines to a file. The easiest way to do this is with the writelines() method.
# open the file in write style myfile = open("sample.txt",'westward') myfile.writelines("Hello Earth!","We're learning Python!") # close the file myfile.close()
We tin as well write multiple lines to a file using special characters:
# open the file in write mode myfile = open("poem.txt", 'w') line1 = "Roses are cerise.\n" line2 = "Violets are blue.\n" line3 = "Python is bang-up.\n" line4 = "And so are you.\due north" myfile.write(line1 + line2 + line3 + line4)
Using string concatenation makes it possible for Python to save text data in a variety of ways.
However, if we wanted to avoid overwriting the data in a file, and instead suspend it or change it, we'd take to open the file using some other file opening mode.
File Opening Modes
By default, Python will open the file in read-only mode. If we desire to exercise annihilation other than just read a file, we'll need to manually tell Python what we intend to do with information technology.
- 'r' – Read Mode: This is the default way for open up() . The file is opened and a pointer is positioned at the commencement of the file'south content.
- 'w' – Write Mode: Using this mode volition overwrite any existing content in a file. If the given file does not exist, a new one will exist created.
- 'r+' – Read/Write Mode: Utilize this mode if you lot demand to simultaneously read and write to a file.
- 'a' – Append Fashion: With this mode the user tin append the data without overwriting any already existing information in the file.
- 'a+' – Append and Read Manner: In this style you can read and suspend the information without overwriting the original file.
- 'ten' – Exclusive Creating Mode: This mode is for the sole purpose of creating new files. Use this mode if you know the file to be written doesn't exist beforehand.
Annotation: 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' grapheme.
# binary files need a special argument: 'b' binary_file = open("song_data.mp3",'rb') song_data = binary_file.read() # shut the file binary_file.close()
Closing Files with Python
After opening a file in Python, it'due south important to shut it later you're done with it. Closing a file ensures that the program tin no longer access its contents.
Close a file with the shut() method.
# open a file myfile = open("poem.txt") # an array to store the contents of the file lines = [] For line in myfile: lines.append(line) # close the file myfile.shut() For line in liens: print(line)
Opening Other File Types
The open up() method can read and write many different file types. Nosotros've seen how to open binary files and text files. Python tin also open images, allowing y'all to view and edit their pixel data.
Before Python can open an image file, the Pillow library (Python Imaging Library) must be installed. It'due south 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 image file img = Image.open("your_image_file.jpg") img.show() img.close()
The Pillow library includes powerful tools for editing images. This has made it 1 of the most popular Python libraries.
With Statement
Y'all can also work with file objects using the with argument. Information technology is designed to provide much cleaner syntax and exceptions treatment when you are working with lawmaking. That explains why it'due south good practice to employ the with statement where applicable.
Ane bonus of using this method is that any files opened volition be closed automatically after you are washed. This leaves less to worry about during cleanup.
To use the with statement to open up a file:
with open("filename") as file:
Now that yous empathise how to call this argument, let'due south take a look at a few examples.
with open("poem.txt") as file: data = file.read() do something with information
You tin as well telephone call upon other methods while using this statement. For case, yous tin do something similar loop over a file object:
with open up("poem.txt") equally f: for line in f: print line,
You'll also observe that in the above example we didn't use the " file.close() " method considering the with argument volition automatically phone call that for us upon execution. Information technology actually makes things a lot easier, doesn't it?
Splitting Lines in a Text File
Every bit a final example, let's explore a unique function that allows you to separate the lines taken from a text file. What this is designed to practice, is split the string independent in variable data whenever the interpreter encounters a space character.
But just considering we are going to use it to dissever lines later a space grapheme, doesn't hateful that's the only way. You tin actually divide your text using any graphic symbol you wish – such equally a colon, for instance.
The lawmaking to do this (as well using a with statement) is:
with open( " hello.text ", "r") equally f: data = f.readlines () for line in data: words = line.dissever () print words
If y'all wanted to use a colon instead of a space to split your text, you would simply alter line.split() to line.carve up(":").
The output for this will be:
["hello", "world", "how", "are", "you", "today?"] ["today", "is", "Saturday"]
The reason the words are presented in this fashion is because they are stored – and returned – as an assortment. Be certain to remember this when working with the split function.
Conclusion
Reading and writing files in Python involves an understanding of the open() method. Past taking advantage of this method'south versatility, it's possible to read, write, and create files in Python.
Files Python tin can either be text files or binary files. It'south also possible to open up and edit image data using the Pillow module.
Once a file's information is loaded in Python, there's almost no stop to what tin be washed with it. Programmers oft work with a large number of files, using programs to generate them automatically.
Equally with any lesson, there is only so much that can be covered in the space provided. Hopefully yous've learned enough to get started reading and writing files in Python.
More Reading
Official Python Documentation – Reading and Writing Files
Python File Handling Cheat Sail
Recommended Python Training
Grade: Python three For Beginners
Over 15 hours of video content with guided instruction for beginners. Acquire how to create real world applications and master the basics.
jeffersonmandiess77.blogspot.com
Source: https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
0 Response to "Python Open a File for Reading and Writing"
Post a Comment