Python Topic 4 basic file knowledge,
This article describes the basics of functions, statements, and strings (similar to other languages ).
1. Basic File Operations
A file is a collection of data stored on external media (such as disks). the operation process of a file is as follows:
Open a file (read/write)-> read/write a file (read/readline/readlines/write/writelines)-> close a file
1. open the file
Open a file by calling the function. The function format is as follows:
File_obj = open (filename [, mode [, buffering]) returns a file object)
-Filename file name (unique mandatory parameter)
· Original string r'c: \ temp \ test.txt'
· Transfer string 'C: \ temp \ test.txt'
-Mode: file mode
· R read mode
· W write mode
· A append mode (written after the last append)
· + Read/write mode (created without files, which can be added to other modes)
· B binary mode (can be added to other modes)
-Buffering buffer (optional)
· Parameter = 0 or False Input/Output I/O is unbuffered, and all read/write operations are performed on hard disks.
· The parameter = 1 or True indicates that the input/output I/O is buffered, and the memory replaces the hard disk.
· Parameter> 1 indicates the buffer size. The unit is byte.-1 or a negative number indicates the default buffer size.
Note: When processing binary files such as audio clips or images in 'B' binary mode, you can use 'rb' to read a binary file.
2. close the file
Keep in mind that the close method is used to close the file, because Python may cache (temporarily store data somewhere for efficiency reasons) and write data. If the program suddenly crashes, the data will not be written to the file at all, for security, close the file after it is used. to disable the file, use the try/finally statement and call the close method in the finally clause. for example:
#Open your file try: #Write data to your file finally: file.close()
3. Read and Write files
Call the function write method to write data to the file. The function format is:
The file_obj.write (string) parameter string is appended to the end of the saved part of the file.
File_obj.writelines (sequence_of_strings) only transmits one parameter, list [] tuples () dictionary {}
Note: When a dictionary is used, the order of strings appears randomly.
# Use write () to write the file file_obj1_open('test.txt ', 'w') str1 = 'Hello \ n' str2 = 'World \ n' str3 = 'python' file_obj.write (str1) file_obj.write (str2) file_obj.write (str3) file_obj.close () # Use writelines () to write file_obj1_open('test.txt ', 'w ') str1 = 'Hello \ n' str2 = 'World \ n' str3 = 'python' file_obj.writelines ([str1, str2, str3]) file_obj.close () # output test.txt file hello word python
Call the read function to read data. The function format is var = file_obj.read (). read reads all data, returns string; readline reads one row, returns string; readlines reads all rows of the file, returns a list of string. example:
# Use read print 'use the read' file_obj1_open('test.txt ', 'R') s = file_obj.read () print s file_obj.close # Use readline print 'use the readline' file_obj1_open('test.txt', 'R ') line1 = file_obj.readline () line1 = line1.rstrip ('\ n') print 'l1', line1 line2 = file_obj.readline () line2 = line2.rstrip (' \ n') print 'l2 ', line2 line3 = file_obj.readline () line3 = line3.rstrip ('\ n') print 'l3', line3 file_obj.close # Use readlines print 'use the readlines' file_obj1_open('test.txt ', 'R ') li = file_obj.readlines () print li file_obj.close
The output content is as follows:
Use the read hello world python Use the readline l1 hello l2 world l3 python Use the readlines ['hello\n', 'world\n', 'python']
It can be found that when the readline () function is used, the returned result is a 'hello \ n' string. You need to use rstrip to remove '\ n'; otherwise, a row is always blank during print output. at the same time, it is convenient to use formatting when writing files, such as s = "xxx % dyyy % s \ n" % (28, 'csdn ').
# Formatting and writing to fd1_open('format.txt ', 'w') head = "%-8 s %-10 s %-10s \ n" % ('id', 'name ', 'record ') fd. write (head) item1 = "%-8d %-10 s %-10.2f \ n" % (10001, 'astmount', 78.9) fd. write (item1) item2 = "%-8d %-10 s %-10.2f \ n" % (10002, 'csdn ', 89.1234) fd. write (item2) fd. close () # output Id Name Record 10001 Eastmount 78.90 10002 CSDN 89.12
Ii. Files and loops
This section describes the basic operations and usage of a file, but file operations are usually linked to loops. The following describes the operations of a while loop and a for loop. The Code is as follows:
# Use the while LOOP fr=open('test.txt ', 'R') str = fr. readline () str = str. rstrip (' \ n') while str! = "": Print str = fr. readline () str = str. rstrip ('\ n') else: print 'end While 'Fr. close # Use for loop rfile1_open('test.txt ', 'R') for s in rfile: s = s. rstrip ('\ n') print s print 'end for 'rfile. close ()
Specifically, for calls the iterator. The iterator provides a method to access each element in an aggregate object in sequence. It is equivalent to obtaining the object's iterator through the Iter function, use the next function (no parameters are required for this method) to obtain the next value. for can traverse iterator_obj including List \ String \ Tuple \ Dict \ File. for example:
S = 'www. csdn. NET 'si = iter (s) # generate the iterator print si. next () # Call next to obtain elements sequentially. When the iterator does not return values, the StopIteration exception is thrown.
Iii. Summary
This article describes the basic knowledge of Python files, including opening, reading, and writing files, closing operations, and reading and writing files and iterators in a loop. hope to help you. If you have any errors or deficiencies, please try again!
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!