Python file operations

Source: Internet
Author: User
Tags readline throw exception

The computer system is divided into three parts: the hardware, the operating system and the application.
1. Memory storage is not long
Persistence of hard disk data
File manipulation--a kind of data persistence
Full stack development: Framework class

Process of manipulating files:

1. #1. Open the file, get the file handle and assign a value to a variable
2. #2. Manipulating a file with a handle
3. #3. Close File

Coding: File Operations
1. Custom called F file f_obj F_handler FH

Copy Code
1. #1. Open the file, get the file handle and assign a value to a variable
2.f=open (' A.txt ', ' R ', encoding= ' utf-8 ') #默认打开模式就为r

    1. 4. #2. Manipulating a file with a handle
      5.data=f.read ()

    2. 7. #3. Close File
      8.f.close ()

Copy Code

F=open (' A.txt ', ' r ') analysis

1. #1, the application initiates a system call to the operating system open (...)
2. #2, the operating system opens the file and returns a file handle to the application
3. #3, application assigns file handle to variable F

1. File path: Relative path, absolute path

Copy Code
1. #找到文件详解: File and py executable file under the same path, directly with the name of the file can open the file

    1. File is not in the same path as the execution file of the PY, find the file with absolute path

      3. #文件的路径, it is necessary to use the method of de-translation: 1.\ 2.R "
      4. #如果以写文件的方式打开一个文件, then the nonexistent file will be created and the contents of the existing file will be emptied
      5.# ' \ n ' file line-break
      6.# f = open (R ' C:\Users\Administrator\Desktop\s8_tmp.txt ', ' W ', encoding= ' utf-8 ') # \
      7.F = open (R ' C:\Users\Administrator\Desktop\s8_tmp.txt ', ' W ', encoding= ' utf-8 ') #文件路径, operating mode, code # R '
      8.f.write (' hahaha ')
      9.f.close ()

Copy Code

Considerations for closing files

Attention
File encoding

Copy Code
1.f = open (' Lyrics ', ' W ', encoding= ' Utf-8 ') #f: file operator file handle file Action object
2.f.write (' 7018201890 ')
3.f.close ()
4. #open打开文件是依赖了操作系统的提供的途径
5. #操作系统有自己的编码, open uses the encoding of the operating system by default when opening files
6. #win7 \8--->gbk mac/linux---->utf-8

Copy Code

1. #这就用到了上节课讲的字符编码的知识: To ensure that it is not garbled, how the file stored in what way, it will open in what way.
2.f=open (' A.txt ', ' R ', encoding= ' utf-8 ')

Open mode of File

1. File handle = open (' File path ', ' mode ')

1. Open File

1. #打开文件
2.# f = open (' lyrics ', ' R ', encoding= ' utf-8 ')
3.F = open (' lyrics ', encoding= ' utf-8 ')

1. Mode

Copy Code
1. #1. The mode of opening the file has (default is text mode):
2.R, read-only mode "default mode, file must exist, not present, throw exception"
3.W, write-only mode "unreadable; not exist" created; empty content "
4.a, the Append write mode is "unreadable; it does not exist, it is created; only append content exists."
5.
6. #2. For non-text files, we can only use B mode, "B" means to operate in bytes (and all files are stored in bytes, using this mode regardless of the text file character encoding, picture file JGP format, video file avi format)
7.rb
8.wb
9.ab
10. Note: When opened in B, the content read is a byte type, and a byte type is required for writing, and encoding cannot be specified

Copy Code

Learn 1

Learn 2

1.f.writable () #判断文件是否可写

1.f = Open (' 1. Lyrics. txt ', ' W ', encoding= "Utf-8")
2.print (F.writable ()) # #判断文件是否可写
3.f.close () # True

1.f.readable () #判断文件是否可读

1.f = Open (' 1. Lyrics. txt ', ' W ', encoding= "Utf-8")
2.print (F.readable ()) # #判断文件是否可写
3.f.close () # False

Read the file

The 1.read method reads all the contents of a file at once

1. #1. The first way to read a file: The Read method, which reads all the contents of the file one time using the Read method
2.f = Open (' 1. Lyrics. txt ', encoding= ' utf-8 ')
3.content = F.read ()
4.print (' read: ', content) #
5.f.close ()

Output results

Copy Code
1.read:111
2.222
3.aaa
4.bbb
5. Wow haha
6.QQ stars

Copy Code

2. Read part of the content: Read (n), specify reading n units

1. #2. Read part: Read (n), specify reading n units
2.f = Open (' 1. Lyrics. txt ', encoding= ' utf-8 ')
3.print (F.read (2)) # 11
4.f.close ()

3. Follow the line reading, and each time you execute ReadLine you will read one line

Copy Code
1. #3. The third way to read a file: read by line, and each time you execute ReadLine you will read one line
2.f = Open (' 1. Lyrics. txt ', encoding= ' utf-8 ')
3.content = F.readline ()
4.print (' ReadLine: ', Content.strip ()) #strip去掉空格, tab, line feed
5.content2 = F.readline ()
6.print (Content2.strip ())
7.f.close ()

Copy Code

Output results

1.readline:111
2.222

4.readlines, returns a list that returns a list of each row in the file as each item in the list

1. #4. The fourth way to read a file: ReadLines, returns a list that returns a list of each line in the file as each item in the list
2.f = Open (' 1. Lyrics. txt ', encoding= ' utf-8 ')
3.content = F.readlines ()
4.print (' readlines: ', content) # ReadLines: [' 111\n ', ' 222\n ', ' aaa\n ', ' bbb\n ', ' wow haha \ n ', ' QQ star ']
5.f.close ()

5. READ: Most commonly used for loops

1. #5. READ: Most commonly used for loops
2.f = Open (' 1. Lyrics. txt ', encoding= ' utf-8 ')
3.for L in F:

    1. Print (L.strip ())
      5.f.close ()

Output results

Copy Code
1.111
2.222
3.aaa
6. bb
5. Wow haha
6.QQ stars

Copy Code

Liezi:

1. Lyrics (. txt)

Results:

1. Read the file and organize it into the required data type

Copy Code
1.f = Open (' 1. Lyrics. txt ', encoding= ' utf-8 ') #读文件并整理成需要的数据类型
2.goods_list = []
3.for line in F:

    1. If Line.strip ():
    2. Goods_dic = {' name ': None, ' Price ': none}
    3. line = Line.strip ()
    4. Goods_lst = Line.split ()
    5. Print (GOODS_LST)
    6. goods_dic[' name '] = goods_lst[0]
    7. goods_dic[' price '] = goods_lst[1]
    8. Goods_list.append (Goods_dic)
      12.print (Goods_list)
      13.f.close ()

Copy Code

Output Result:

Results: 1.2. Display only rows with content in the file

Copy Code
1.f = Open (' 1. Lyrics. txt ', encoding= ' utf-8 ') #只显示文件中有内容的行
2.goods_list = []
3.for line in F:

    1. If Line.strip ():
    2. Print (Line.strip ())
      6.f.close ()

Copy Code

Output Result:

Results:

Cursor movement within a file

One: Read (3):

1. When the file is opened in text mode, the representation reads 3 characters

2. When the file is opened in B mode, the delegate reads 3 bytes

Second: The rest of the files within the cursor movement are in bytes such as Seek,tell,truncate

Attention:

1. Seek has three modes of movement 0,1,2, of which 1 and 2 must be performed in B mode, but regardless of which mode is moved in bytes units

Explanation of Seek parameters
2. Truncate is to truncate the file, so the file must be opened in a way that can be written, but cannot be opened with W or w+, because that will directly empty the file, so truncate to r+ or a or a + and other modes to test the effect

1. #tell: Tell you where the cursor is currently located

Tell

1. #seek the cursor to the position of the first few bytes
# f.seek (0) move to the very beginning
# F.seek (0,2) move to the very end

1.
#truncate: N bytes reserved
Ps:
  

1.txt1.
Preserves only the contents of the specified bytes from the beginning of the file

1.f = Open (' 1. Lyrics. txt ', ' r+ ', encoding= ' utf-8 ')
2.f.truncate (3) #从文件开始的位置只保留指定字节的内容
3.content2 = F.readline ()
4.print (Content2.strip ()) # AAB
5.f.close ()

viewing 1.txt files, it has been modified, only aab3 bytes.

Modification of files

File data is stored on the hard disk, so there is only coverage, there is no modification so to speak, we usually see the modified files, are simulated out of the effect, specifically, there are two ways to achieve:

Mode one: The contents of the file stored in the hard disk are loaded into memory, can be modified in memory, and then overwritten by memory to the hard disk (word,vim,nodpad++ and other editors).

Copy Code
1.import OS
2.
3.with open (' a.txt ') as Read_f,open ('. A.txt.swap ', ' W ') as Write_f:

    1. Data=read_f.read () #全部读入内存, if the file is large, it will be very card
    2. Data=data.replace (' Alex ', ' SB ') #在内存中完成修改
    3. Write_f.write (data) #一次性写入新文件
    4. 9.os.remove (' A.txt ')
      10.os.rename ('. A.txt.swap ', ' a.txt ')

Copy Code

Mode two: The contents of the file stored on the hard disk are read into memory line by line, the modification is completed to write a new file, and finally overwrite the source file with a new file

Copy Code
1.import OS
2.
3.with open (' a.txt ') as Read_f,open ('. A.txt.swap ', ' W ') as Write_f:

    1. For line in Read_f:
    2. Line=line.replace (' Alex ', ' SB ')
    3. Write_f.write (line)
    4. 8.os.remove (' A.txt ')
      9.os.rename ('. A.txt.swap ', ' a.txt ')

Python file operations

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.