Read, write, and Python
In previous articles in the Explore Python series, you learned about basic Python data types and some container data types, such as tuple
, string
and list
. Other articles discuss the conditions and looping characteristics of the Python language and how they collaborate with the container data types to simplify programming tasks. The last basic step in writing a program is to read the data from the file and write the data to the file. After reading this article, you can add a task that examines the effect of this skill learning in your to-do list.
Simple output
Throughout the series, a print
statement is written to (output) data, which by default string
writes the expression to the screen (or Console window). Listing 1 illustrates this. Listing 1 repeats the first Python program "Hello, world!", but makes some minor tweaks.
Listing 1. Simple output
>>> print "Hello world!" Hello world!>>> Print "The total value was = $", 40.0*45.50the total value was = $1820.0>>> print "The To Tal value = $%6.2f "% (40.0*45.50) The total value = $1820.00>>> myfile = File (" Testit.txt ", ' W ') >>> Prin T >> myfile, "Hello world!" >>> print >> myfile, "the total value = $%6.2f"% (40.0*45.50) >>> myfile.close ()
As this example demonstrates, print
it is easy to write data with a statement. First, the sample output is a simple one string
. It then creates and outputs the composite string
, which is created using the string
format technique.
After that, however, things changed, unlike previous versions of the code. The next line creates file
the object, passing in the name "testit.txt"
and ‘w‘
character (written to the file). Then use the modified statement--the print
two greater than sign followed by the file
variable that holds the object--writes the same string
. But this time, the data is not displayed on the screen. The natural question is: Where did the data go? And, file
what is this object?
The first question is an easy one to answer. Please look for the Testit.txt file and display its contents as shown below.
% more Testit.txt Hello world! The total value = $1820.00
As you can see, the data is written to the file exactly as it was previously written to the screen.
Now, notice the last line in Listing 1, which invokes file
the method of the object close
. This is important in a Python program because the file input and output are buffered by default, and the print
data is not actually written when the statement is invoked, instead, the data is written in batches. The simplest way for Python to write data to a file is to explicitly invoke the close
method.
File Object
file
is the basic mechanism for interacting with files on a computer. You can use file
objects to read data, write data or add data to a file, and work with binary or textual data.
The easiest way to learn file
about objects is to read Help, as shown in Listing 2.
Listing 2. Get help with File object
>>> Help (file), on the class file in module __builtin__:class file (object) | File (name[, mode[, buffering]), file object | | Open a file. The mode can is ' R ', ' W ' or ' A ' for reading (default), | Writing or appending. The file would be created if it doesn ' t exist | When opened for writing or appending; It'll be truncated when | Opened for writing. Add a ' B ' to the mode for binary files. | Add a ' + ' to the mode to allow simultaneous reading and writing. | If The buffering argument is given, 0 means unbuffered, 1 means line | Buffered, and larger numbers specify the buffer size. | Add a ' U ' to mode-open the file for input with Universal newline | Support. Any line ending in the input file would be seen as a ' \ n ' | In Python. Also, a file so opened gains the attribute ' newlines '; | The value for this attribute is one of None (no newline read yet), | ' \ r ', ' \ n ', ' \ r \ n ' or a tuple containing all the newline types seen. | | ' U ' cannot is combined with 'W ' or ' + ' mode. | | Note:open () is a alias for file (). | | Methods defined here: ...
As the help tool points out, using file
objects is simple. file
open
Create an object with a constructor or method file
, and Open is file
the alias of the constructor. The second parameter is optional and specifies how the file is to be used:
‘r‘
(the default value) indicates that data is read from a file.
‘w‘
Indicates that you want to write data to a file and truncate the previous content.
‘a‘
Represents the data to be written to the file, but is added to the current content trailer.
‘r+‘
Represents a read-write operation on a file (deleting all previous data).
‘r+a‘
Represents a read-write operation to a file (added to the end of the current content).
‘b‘
Indicates that you want to read and write binary data.
The first code listing for this article writes data to a file. Now, listing 3 shows how to read this data into a Python program and parse the contents of the file.
Listing 3. Reading data from a file
>>> myfile = open ("Testit.txt") >>> myfile.read () ' Hello world!\nthe total value = $1820.00\n ' >>& Gt str = myfile.read () >>> print str>>> myfile.seek (0) >>> str = myfile.read () >>> Print Strhello world! The total value = $1820.00>>> str.split () [' Hello ', ' world! ', ' the ', ' total ', ' value ', ' = ', ' $1820.00 ']>>&G T Str.split (' \ n ') [' Hello world! ', ' the total value = $1820.00 ', ']>>> for line in Str.split (' \ n '): ... Print Line ... Hello world! The total value = $1820.00>>> myfile.close ()
To read the data, first create the appropriate file
object-in this example, the file object opens the Testit.txt file and uses the read
method to read the content. This method reads the entire file into one and string
then outputs the string to the console in the program. In the read
second call to the method, an attempt was made to assign a value to the str
variable, and the result returns an empty one string
. This is because the first read operation reads the entire file. When I try to read the content again, it has reached the end of the file, so I can't read anything.
The solution to this problem is also simple: let the file
object return to the beginning of the file. Go back to the beginning by seek
means of a method that takes a parameter that indicates where to start reading or writing from within the file (for example, 0 represents the beginning of the file). seek
the method supports more complex operations, but can be dangerous. For now, we're sticking with the simple way.
Now back to the beginning of the file, you can read the contents of the file into the string
variables and string
parse them appropriately. Note that in the file, the rows are distinguished by the new line (or line end) character. If you try to string
raise the split
method, it splits in white space characters, such as spaces. In order for the method to split rows according to New line characters, you must explicitly specify new line characters. You can then split string
and iterate through the lines of the file in a for
loop.
It seems that there is much work to be done to read and process a single line of content from a file. Python makes simple things easier, so you might want to know if there are any shortcuts available for this task. As shown in Listing 4, the answer is yes.
Listing 4. Reading and parsing rows
>>> myfile = open ("Testit.txt") >>> for Line in Myfile.readlines (): ... Print Line ... Hello world! The total value = $1820.00>>> myfile.close () >>> for line in open ("Testit.txt"). ReadLines (): ... Print Line ... Hello world! The total value = $1820.00>>> to line in open ("Testit.txt"): ... Print Line ... Hello world! The total value = $1820.00
Listing 4 shows the three techniques for reading and parsing text file rows. First, open the file and assign it to the variable. The method is then called to readlines
read the entire file into memory and split the contents into a string
list. for
loops iterate over the string
list, outputting one line at a time.
The second for
Loop file
simplifies the process slightly by using an implicit variable of the object (that is, the variable is not explicitly created). Opening a file and reading the contents of the file is completed once, and the resulting effect is the same as the first explicit example. The last example further simplifies and demonstrates the file
ability to iterate directly on an object (note that this is a new feature of Python, so it may not work on your computer). In this example, you create an implicit file
object, and then Python does the rest of the work, allowing you to iterate through all the lines in the file.
Sometimes, however, you might want a better level of control when reading data from a file. In this case, the method should be used readline
, as shown in Listing 5.
Listing 5. Reading data
>>> myfile = open ("Testit.txt") >>> myfile.readline () ' Hello world!\n ' >>> myfile.readline () ' The total value = $1820.00\n ' >>> myfile.readline () ' >>> myfile.seek (0) >>> Myfile.readline () ' Hello world!\n ' >>> Myfile.tell () 13l>>> myfile.readline () ' The total value = $1820.00\n ' >> > Myfile.tell () 40l>>> myfile.readline () ">>> Myfile.tell () 40l>>> myfile.seek (0) > >> Myfile.read (+) ' Hello world!\nthe ' >>> myfile.seek (0) >>> myfile.readlines (+) [' Hello World!\n ', ' the total value = $1820.00\n ']>>> myfile.close ()
This example shows how to move through a file, read one line at a time, or explicitly seek
move a file position indicator with a method. First, use readline
the method to move through the file line. When the end of the file is reached, readline
the method returns an empty one string
. After the end of the file, if you continue reading in this way, it will not cause an error and will only return empty string
.
It then returns where the file started and reads another line. The tell
method shows the current position in the file (after the first line of text)-In this example, the 13th character position. By using this knowledge, you can read
readline
pass a parameter to the or method that controls the number of characters read. For a read
method, this parameter (in this case, 17) is the number of characters to read from the file. However readline
, after reading the specified number of characters, the method continues to read until the end of the line. In this example, it reads the first and second lines of text.
Write Data
Examples so far have focused on reading data rather than writing it. But as listing 6 shows, writing is easy once you understand the file
basics of using objects.
Listing 6. Write Data
>>> mydata = [' Hello world! ', ' the total value = $1820.00 ']>>> myfile = open (' t Estit.txt ', ' W ') >>> in MyData: ... myfile.write (line + ' \ n ') ... >>> myfile.close () >>&G T MyFile = open ("Testit.txt") >>> myfile.read () ' Hello world!\nthe total value = $1820.00\n ' >>> Myfile.close () >>> myfile = open ("Testit.txt", "r+") >>> for line in MyData: ... myfile.write (line + ' \ N ') ... >>> myfile.seek (0) >>> myfile.read () ' Hello world!\nthe total value = $1820.00\n ' >>> Myfile.close () >>> myfile = open ("Testit.txt", "R+a") >>> myfile.read () ' Hello world!\nthe total value = $1820.00\n ' >>> for line in MyData: ... myfile.write (line + ' \ n ') ... >>> myfile.seek (0) >>> my File.read () ' Hello world!\nthe total value = $1820.00\nhello world!\nthe Total value = $1820.00\n ' >>> myfile.clos E ()
To write data to a file, you must first create the file
object. However, in this case, you must ‘w‘
specify the file to be written with a pattern token. In this example, the contents are written to the file, the file is mydata list
closed, and then the file is reopened so that the contents can be read.
However, in general, you want to read files and write files at the same time, so the next part of the example ‘r+‘
re-opens the file in mode. The file is truncated because it can be written to and not added. First, the mydata list
content is written to the file, then the file pointer is relocated to the beginning of the file and read into the content. This example then closes the file and re-opens it in read and add mode "r+a"
. As the sample code shows, the file contents are now the result of two write operations (the text is duplicated).
Processing binary data
All previous examples deal with text data or character data: writing and reading characters string
. However, in some cases, such as when working with integers or compressing files, you need to be able to read and write binary data. file
When you create an object, ‘b‘
you can easily process the binary data in Python by adding it to the file mode, as shown in Listing 7.
Listing 7. Processing binary data
>>> myfile = open ("Testit.txt", "WB") >>> for C in range (+): ... Myfile.write (Chr (c)) ... >>> myfile.close () >>> myfile = open ("Testit.txt") >>> Myfile.read ( ) ' 23456789:;<=>[email protected] ' >>> myfile.close ()
In this example, create an appropriate object and file
write the binary character with an ASCII value from 50 to 69. Use the chr
method to convert range
the integer created by the method call into a character. After all the data has been written, close the file and reopen the file for reading, or use binary mode notation. Reading a file proves that the integer is not written to the file, but instead writes a character value.
You must be careful when reading and writing binary data, because different platforms store binary data in different ways. If binary data must be processed, it is best to use the appropriate objects from the Python library (or objects from third-party developers).
Back to top of page
Read and write: The most interesting places
This article discusses how to read data from a file and write data to a file in a Python program. Overall, the process is simple: Create the appropriate file
object and then read and write as needed. However, when you create a file by using write mode file
, you must be aware of the truncation of the file when you write data to the file. If you need to add data to a file, file
you should use Add mode when you create the object.
Reprint Link: https://www.ibm.com/developerworks/cn/opensource/os-python8/
Reprint-python Learning notes input/output function read and write data