Getting Started with Python basics-file read/write

Source: Internet
Author: User
Tags save file

The file read and write operations in Python should be very extensive. For example, we often read txt to get some information for parameterized operations. When the heat is not limited to these, there is a lot of knowledge about the document reading and writing, saying that one day may not be finished, but we today? The main share with you is the Python file read and write some of the more practical, we often use the knowledge. Let's start the show ~ ~ ~

How do you create a file in Python? We can use the open () function, which has a lot of parameters and a look at its basic body:

        Open (name[, mode[, Buffering]) name: A string value that contains the name of the file you want to access. Mode:mode determines the mode of opening the file: read-only, write, append, etc. All the desirable values are shown in the full list below. This parameter is non-mandatory and the default file access mode is read-only (R). Buffering: If the value of buffering is set to 0, there is no deposit. If the value of buffering is 1, the row is stored when the file is accessed. If you set the value of buffering to an integer greater than 1, it indicates that this is the buffer size of the storage area. If a negative value is taken, the buffer size of the storage area is the system default.

In this I can simply understand is: open (file path, open mode) as for the value of buffering we can ignore, later. When using the Open function, we also need to know one thing, is about the file commonly used in reading and writing methods? Let's take a look at this:

Read the file:

Read (n byes)    reads N bytes readline () The      default reads the first line, the array returns ReadLines ()     reads all the contents of the line, returns the array as

Write file:

Write () write         directly to the content Writelines ()    writes a sequence string to a file line wrap using \ n
A Append file

1. We first use the Open function to create a file named demo.py W: Write mode to open the file, write mode overwrites the original file content, if the file does not exist the creation

filename = open (' Test.txt ', ' W ') filename.write (' www.baidu.com ') filename.close ()

Code parsing:

1). We use the Open function to create a test.txt file, we use the Write (W) pattern created, this is important, otherwise cannot create the file

2). We use the Write method to write www.baidu.com content to the Text.txt file

3). Close () is used to close the file, and the file is not closed and is not actually committed to memory.

Output Result:

Because no specific storage path is specified, the files created by default are together with the demo.py file.

Open the file to see the contents:

See if Www.baidu.com was written to the Test.txt file?

Add: We use Writelines to write the sequence object to the txt text.

#写文件f = open (' Tex.txt ', ' W ') f.writelines ([' Python ', ' java ', ' php ']) f.close () #读文件 we are using readlines below there will be a specific introduction to F = open (' Tex.txt ', ' R ') print F.readlines ()

Output Result:

[' pythonjavaphp ']

Warm tip: Writelines () can only write the sequence to the file, not the sequence will be an error, I see an example of an error.

f = open (' Tex.txt ', ' W ') f.writelines ([1,234, ' php ']) f.close () F = open (' Tex.txt ', ' R ') print F.readlines ()

We replaced the python with a constant 1,234 to see the result of the output:

  File "e:/project_case/demo.py", line +, in <module>    f.writelines ([1,234, ' php ']) typeerror:writelines () Argument must be a sequence of strings

The program is not error ~ ~ ~ ~ ~!!!

2. How do we read the contents of a file? The way to read the file is read (r) mode, look at the example just now.

#读文件filename = open (' Test.txt ', ' W ') filename.write (' www.baidu.com ') filename.close () #写文件read_file = open (' Test.txt ', ' r ') result = Read_file.read () print result

Code parsing, we write the file using the Open function, the pattern is R (read mode), read by default read () reads the entire content. The output results are as follows:

Www.baidu.com

Looking at the results of reading using ReadLines?

#读文件filename = open (' Test.txt ', ' W ') filename.write (' www.baidu.com ') filename.close () #写文件read_file = open (' Test.txt ', ' r ') result = Read_file.readline () print result

Also reads the first line because there is only one line in the Test.txt file. Instead, ReadLine reads one line of content by default. Let's continue to look at the results of reading files using ReadLines. This time we add a few lines of content to the Test,txt file. We copied the www.baidu.com 7 times and then read the Test.txt file using ReadLines to see the following code:

#读文件read_file = open (' Test.txt ', ' r ') result = Read_file.readlines () print result

The output results are as follows:

[' www.baidu.com\n ', ' www.baidu.com\n ', ' www.baidu.com\n ', ' www.baidu.com\n ', ' www.baidu.com ']

Store all the content in the list and return it to us. But another one's disgusting. Because the content of each of our lines has been changed after the completion of the operation of the line, the line character directly printed out. Can you get rid of this damn thing? The answer is of course you can. Keep looking down:

#读文件read_file = open (' Test.txt ', ' r ') result = Read_file.readlines () for  i in  result:    print i.strip (' \ n ')

The purpose of the strip function is to take the extracted content out of the line break operation. The output results are as follows:

Www.baidu.comwww.baidu.comwww.baidu.comwww.baidu.comwww.baidu.com

3. Append content to file, use a mode, this way does not overwrite the original content of the file. First we have to have the content of existence. Look at one end of the code snippet:

#读文件 the contents of the #test.txt file, we continue to append content on this basis. Read_file = open (' Test.txt ', ' a ') read_file.write (' Zhangshan ' + ' Lishi ' + ' Meiguo ') Read = open (' Test.txt ', ' R ') print Read.readlines ()

The output results are as follows:

[' Welcome to China ', ' Zhangshanlishimeiguo ']

4. Add the following at the end of the newline:

Read_file = open (' Test.txt ', ' a ') read_file.write (' \ n ' + ' Zhangshan ' + ' Lishi ' + ' Meiguo ') Read = open (' Test.txt ', ' R ') print Read.readlines ()

Output Result:

[' \ n ', ' Zhangshanlishimeiguo ']

5. If we open a file that does not exist, the system throws an error. Look at the following code:

Read = open (' Abc.txt ', ' R ') print Read.readlines ()

The output error message is as follows:

Traceback (most recent call last):  File "e:/project_case/demo.py", line +, in <module>    read = open (' Abc.tx T ', ' R ') IOError: [Errno 2] No such file or directory: ' Abc.txt '

6. Let's take a look at the file's built-in properties

The file () method is      used to create new files (as with open). The name () method  is used to get the file name. Closed ()       checks if the file is closed successfully returns TRUE if the  error returns false. Close () method   Close File

code example:

fn = file (' T1.txt ', ' W ')   new file Fn.write (' asdf ')          Write ASDFF = open (' T1.txt ', ' r ')    read files print f.closed            Check whether print f.readlines () is successfully turned off       printing all lines

Operation Result:

false[' ASDF ']

7. Do not need to check file closed read and write file method:

  with open (' Test1.txt ', ' W ')  as  F:    f.write (' Hellozhongguo ')    f.close ()    print f.closed

return Result:

True

We use the with open (file name, ' Read and write mode ') as F: To create the file in the read file.

Source code Example:

#创建文件with  Open (' Test1.txt ', ' W ')  as  F:    f.write (' Hellozhongguo ')    f.close ()    Print f.closed# read file  with open (' Test1.txt ', ' R ')  as  f:    read_type = F.readlines ()    print Read_type

Output Result:

true[' Hellozhongguo ']

Let's continue with an example to deepen our understanding of the second approach:

The From datetime import datetime# writes the file with open (' Test.txt ', ' W ') as F:    F.write (' Today is ')    F.write (DateTime.Now (). Strftime ('%y-%m-%d '))

Use datetime to get the current time, and write to the file, and then make a read of the file.

#读文件with open (' Test.txt ', ' R ') as F:    s = f.read ()    print (' Open for read ... ')    print (s)

Output Result:

Open for Read ... Today is 2018-01-13

Is it easier and more convenient to read and write files in a way that compares the first reading?

8. How to use the read binary file in file reading and writing

Binary files specify the images, videos, including. HTML-formatted pages, and so on, so how do you read them using file reads and writes? First we need to know that the way to read the binary is ' WB ' mode. For example, we open a binary file with a local hello.jpg format file.

#打开一个二进制文件with Open ("e:\\project_case\\python_base\\read_file\\hello.jpg1", ' RB ') as  f:    a = F.read ()    Print a

The result returned is a lot of garbled characters. When hot, we're just introducing this way of reading binary files.

9. Reading encoding setup issues in the file

9.1) If the saved TXT file format is in ASN format, the Chinese content can be output in the following way:

With open ("123.txt", ' RB ') as F:    s = F.read (). Decode (' GBK ')    print S

Code parsing:

1. RB for reading files of course, it's also possible to switch to R mode.

2.. decode (' GBK ') mode is used to ensure normal Chinese output, because the encoding of Windows is GBK

3. Print the contents of the file

View results:

Non-ASCII code file 1) ANSI is the default encoding method. For English documents is ASCII encoding for Simplified Chinese files is GB2312 encoded (only for Windows Simplified Chinese version, if the traditional Chinese version will use BIG5 code). If it is troublesome to manually convert the code every time (write a program afraid of trouble is good, not afraid of trouble will write long and difficult to understand and can not maintain the code), Python also provides a codecs module for us to read the file automatically converted code, directly read the Unicode:

9.2) How we set the TXT file format to the ' utf-8 ' format, then the wording on the above is very different. First change the TXT save file ("Utf-8") and then read the file characters.

Then use the code to output:

#读取文件保存为utf-8 format with open ("Abc.txt", ' RB ') as F:    s = F.read (). Decode (' Utf-8 ')    print S

The output results are as follows:

Today is 21:00utf-8 is the most widely used Unicode implementation in the Internet. Other implementations include UTF-16 and UTF-32, but they are largely unused on the Internet. Again, the relationship here is that UTF-8 is one of the ways Unicode is implemented. One of the biggest features of UTF-8 is that it is a variable-length coding method. It can use 1~4 bytes to represent a symbol, varying the length of a byte depending on the symbol.

We'll introduce you to the contents of the file read and write.

Getting Started with Python basics-file read/write

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.