22nd Python File Basics

Source: Internet
Author: User

computer = instruction + data

(CPU execution) (stored in RAM)

The computer reads the contents of the file into memory, which is actually assigned to a variable.

File Operation Flow:

    • Open file: Establish the connection between the program and the file

--Reading Mode

--writing method

    • Read and write files

--file_obj.read, File_obj.readline, File_obj.readlines

--file_obj.write, File_obj.writes

    • Close File

File_obj.close ()

Memory----->io Buffer----> Save to disk


Open File

File_obj=open (Filename,mode)

-filename:

Original string: R ' C:\temp\text.t ' #me: The path under Linux is/, so it is not treated as a special

Escape string: ' c:\\temp/test.t '

The above two are equivalent

-mode

R (), W (), A (), B ()

R+ (), w+ (), A + () append, if the file does not exist, create

    1. Read the file

      Var=file_obj.read ()

      -read all read back--return string

      -readline reads a line--Returns a string

      -readlines read multiple lines-Returns a list of string (list)

    2. Write file:

      File_obj.write (Content_obj)

      -write f.write (content_obj + ' \ n ')

      -writelines

    3. Close File

      File_obj.close ()

    4. Remove the ' \ n ' from the read-back string

      Str=str.rstrip (' \ n ') rstrip--> removes the right-most

      Because ReadLine---> string + ' \ n ', print comes with a return key ' \ n ', so if you don't do it, you'll make a blank line.

    5. Reading and writing of numeric data

      When writing, use STR to convert to string + ' \ n '

      When reading back, use int, float to convert to numeric data.

      ' \ n ' is a non-printable character in ASCII

Eg1:file_obj=open ('/home/wuxy/test.txt ', ' R ')

S=fiel_obj.read ()---A string

Print S

File_obj.close ()


















22nd Python File Basics

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.