Python Learning note 9-Files

Source: Internet
Author: User

Open File

The default is open in R, read-only mode

>>> f = open ("/test/demo.txt") for in F:   ... Print line,      #后面加一个逗号, removed the original default added \ n, less empty lines. . .. hellopython

Write a file

"W": Open the file in writing and write information to the file. If the file exists, the file is emptied, the new content is written, and the file is created if it does not exist

>>> f1 = open ("/test/demo.txt","w")> >> f1.write ("hello,python")>>> f1.close ()

"A": Open the file in Append mode (that is, an open file, the file pointer is automatically moved to the end of the file), if the file does not exist, create

>>> F2 = open ("/test/demo22.txt","a")> >> f2.write ("I like c\n")>>> f2.close ()

Using the WITH

There is no need for close (). And this approach is more of a Python flavor, or more in line with Pythonic's requirements.

>>> with open ("/test/demo.txt","a") as f: ...  f.write ("HelloWorld">>> with open ("/test/demo.txt", "R ") as F:
... print f.read ()

Hello,pythonhello World

Get file status

>>>ImportOS>>> File_stat = Os.stat ("131.txt")>>>file_stat Posix.stat_result (St_mode=33188, st_ino=7077890, st_dev=64768, St_nlink=1, St_uid=0, St_gid=0, st_size=14, st_atime=1473126833, st_mtime= 1473126819, st_ctime=1473126819)>>>File_stat.st_ctime1473126819.3923097>>>ImportTime#introducing time modules, converting times>>>time.localtime (file_stat.st_ctime) time.struct_time (tm_year=2016, tm_mon=9, tm_mday=6, tm_hour=9, tm_min=53, tm_sec=39, Tm_wday=1, tm_yday=250, tm_isdst=0)

Read/readline/readlines

    • READ: If the parameter size is specified, the content is read from the file according to the specified length, otherwise the full text is read. The contents are read out and stuffed into a string. This has the advantage, is the thing all to the memory, at any time to use, relatively fast, "Analyticals defeated Xiao", also because of this, if the file content too much, memory will be unbearable. The document has been alerted to issues in "non-blocking" mode
>>> f = open ("You.md")
>>> content = F.read ()
>>> Content
' You Raise Me up \nwhen I am down and, oh my soul, so weary; \nthen troubles come and my heart burdened be; \ n '
>>> Print Content




>>> F.close ()
    • ReadLine: The optional parameter size has the same meaning as above. It returns a string in the behavior unit, that is, every time a line is read, looping, if the size is not qualified until the last empty string is returned, it means the end of the file (EOF).
>>> F.readline ()
' You Raise Me up \ n '
>>> F.readline ()
' When I am down and, oh my soul, so weary; \ n '
>>> F.readline ()
' Then troubles come and my heart burdened is; \ n '
>>> F.readline ()
‘‘
>>> F.close ()

Complete a read of the entire file with a looping statement

# /usr/bin/env python # coding=utf-8f = open ("/python/you.md") while True:    = f.readline ()    if not line :        #到 EOF, returns an empty string, terminates the      loop  Break    Print line,         #注意后面的逗号, remove the ' \ n ' after the print statement, leaving the newline f.close () in the original file
    • Readlines:size Ibid. It returns a list of behavior units, that is, the equivalent of executing readline (), getting each row, and then putting the string of that line into a list as an element in the list, and finally returning the list.
>>> f = open ("You.md")
>>> content = F.readlines ()
>>> Content
[' You Raise Me up \ n ', ' when I am down and, oh my soul, so weary; \ n ', ' then troubles come and my heart burdened is; \ n ']

>>> for line in content: #使用循环取出
.. print line,



Then troubles come and my heart burdened be;

Read a lot of files

If the file is too large, you cannot use Read () or readlines () to read all the contents into memory at once, and you can use the while loop and Readlin () to accomplish this task.
In addition, there is a method: Fileinput module

Import Fileinput  for  in Fileinput.input ("you.md  "): ... Print And and my heart burdened be;   

There is one more common method

>>> f = open ("you.md") for in F:   ... Print  and and>>> f.close ()

This is possible because file is an iterative data type that can be iterated directly with for.

Seek

The function is to let the pointer move. Note, in particular, that it is moved in bytes. Like what:

>>> f = open ("you.md")>>> f.readline ()' You Raise Me up \ n '>>> f.readline ()'whenI am down and, oh my soul, so weary; \ n' >>> f.seek (0)>>> f.readline ()'youRaise Me up \ n' 

The position at which the pointer is located can also be displayed with a tell (), as

>>> F.tell ()17

Python Learning note 9-Files

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.