Python Action on files

Source: Internet
Author: User

file operation:

Procedure for file operation

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

The existing files are as follows

Somehow, it seems the love I knew was always the most destructive kind

不知为何,我经历的爱情总是最具毁灭性的的那种

Yesterday when I was young

昨日当我年少轻狂

The taste of life was sweet

生命的滋味是甜的

As rain upon my tongue

就如舌尖上的雨露

I teased at life as if it were a foolish game

我戏弄生命 视其为愚蠢的游戏

The way the evening breeze

就如夜晚的微风

May tease the candle flame

逗弄蜡烛的火苗

The thousand dreams I dreamed

我曾千万次梦见

The splendid things I planned

那些我计划的绚丽蓝图

I always built to last on weak and shifting sand

但我总是将之建筑在易逝的流沙上

I lived by night and shunned the naked light of day

我夜夜笙歌 逃避白昼赤裸的阳光

And only now I see how the time ran away

Basic operations

f =open(‘lyrics‘) #打开文件

first_line =f.readline()

print(‘first line:‘,first_line) #读一行

print(‘我是分隔线‘.center(50,‘-‘))

data =f.read()# 读取剩下的所有内容,文件大时不要用

print(data) #打印文件

f.close() #关闭文件

The mode of opening the file is:

    • R, read-only mode (default).
    • W, write-only mode. "unreadable; not exist; create; delete content;"
    • A, append mode. "Readable; not exist" create; "only append content;"

"+" means you can read and write a file at the same time

    • r+, can read and write files. "readable; writable; can be added"
    • w+, write and read
    • A +, with a

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

    • RU
    • R+u

"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)

    • Rb
    • Wb
    • Ab

Other syntax

    def close (self): # real signature unknown;                Restored from __doc__ "" "Close the file.  A closed file cannot is used for further I/O operations.        Close () May is called more than once without error. "" "Pass Def Fileno (self, *args, **kwargs): # Real signature Unknown" "" Return the underlying file descr Iptor (an integer).  "" "Pass Def Isatty (self, *args, **kwargs): # Real signature Unknown" "" True if the file was connected to A TTY device. "" "Pass Def Read (self, size=-1): # known case of _io.                Fileio.read "" "Note that you may not be able to read it all back. Read at the most size bytes, returned as bytes.        Only makes one system call, so less data is returned than requested.        In non-blocking mode, returns None if the data is available.        Return an empty bytes object at EOF. "" "" Return "" Def readable (self, *args, **kwargs): # Real signature Unknown "" "True If File is opEned in a read mode. "" "Pass Def ReadAll (self, *args, **kwargs): # Real signature Unknown '" "" Read all data from the F                Ile, returned as bytes.  In non-blocking mode, returns as much as are immediately available, or None if no data is available.        Return an empty bytes object at EOF. "" "Pass Def Readinto (self): # real signature unknown;        Restored from __doc__ "" "Same as Rawiobase.readinto ()." "" Pass #不要用, no one knows what it's for. Def seek (self, *args, **kwargs): # Real signature Unknown "" "Move to new file posit                Ion and return the file position.  Argument offset is a byte count. Optional argument whence defaults to Seek_set or 0 (offset from start of file, offset should be >= 0); Other values is seek_cur or 1 (move relative to current position, positive or negative), and seek_end or 2 (move relative to end of file, usually negative, although many platforms allow SEeking beyond the end of a file).        Note that not all file objects is seekable. "" "Pass Def seekable (self, *args, **kwargs): # Real signature Unknown" "" True if file supports Random-a Ccess.                "" "Pass Def Tell (self, *args, **kwargs): # Real signature Unknown '" "" Current file position.        Can raise oserror for non seekable files.  "" "Pass def truncate (self, *args, **kwargs): # Real signature unknown '" "truncate the file to at                Most size bytes and return the truncated size.        Size defaults to the current file position, as returned by Tell ().        The current file position was changed to the value of size. "" "Pass Def writable (self, *args, **kwargs): # Real signature Unknown" "" True if file is opened in a W Rite mode. "" "Pass Def write (self, *args, **kwargs): # Real signature Unknown '" "" Write bytes B to file, ret Urn NumbEr written.        Only makes one system call, so is not all of the data is written.  The number of bytes actually written is returned.        In non-blocking mode, returns None if the write would block. "" "Pass

With statement

To avoid forgetting to close a file after opening it, you can manage the context by:

with open(‘log‘,‘r‘) as f:

...

This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.

After Python 2.7, with also supports the management of multiple file contexts simultaneously, namely:

with open(‘log1‘) as obj1, open(‘log2‘) as obj2:

pass

Python Action on 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.