Python Basic Learning

Source: Internet
Author: User

File operations

Text files can store too much data: weather data, traffic data, socio-economic data, literary works, and so on. Reading a file is useful whenever you need to modify the information stored in a file after parsing it, especially for data analysis applications. The process of learning files allows the program to quickly analyze large amounts of data.

1. Procedures for the operation of files:

First open the file, get the file handle and assign a value to a variable, and then through the handle to the file operation, after the operation is finished, finally close the 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 事到如今我才看清岁月是如何匆匆流逝 Yesterday when I was young 昨日当我年少轻狂 So many lovely songs were waiting to be sung 有那么多甜美的曲儿等我歌唱 So many wild pleasures lay in store for me 有那么多肆意的快乐等我享受 And so much pain my eyes refused to see 还有那么多痛苦 我的双眼却视而不见 I ran so fast that time and youth at last ran out 我飞快地奔走 最终时光与青春消逝殆尽 I never stopped to think what life was all about 我从未停下脚步去思考生命的意义 And every conversation that I can now recall 如今回想起的所有对话 Concerned itself with me and nothing else at all 除了和我相关的 什么都记不得了 The game of love I played with arrogance and pride 我用自负和傲慢玩着爱情的游戏 And every flame I lit too quickly, quickly died 所有我点燃的火焰都熄灭得太快 The friends I made all somehow seemed to slip away 所有我交的朋友似乎都不知不觉地离开了 And only now I‘m left alone to end the play, yeah 只剩我一个人在台上来结束这场闹剧 Oh, yesterday when I was young 噢 昨日当我年少轻狂 So many, many songs were waiting to be sung 有那么那么多甜美的曲儿等我歌唱 So many wild pleasures lay in store for me 有那么多肆意的快乐等我享受 And so much pain my eyes refused to see 还有那么多痛苦 我的双眼却视而不见 There are so many songs in me that won‘t be sung 我有太多歌曲永远不会被唱起 I feel the bitter taste of tears upon my tongue 我尝到了舌尖泪水的苦涩滋味 The time has come for me to pay for yesterday 终于到了付出代价的时间 为了昨日 When I was young 当我年少轻狂

Basic operations

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

First_line = F.readline ()

Print ("First line:", First_line) #读一行

Print (' I am split line '. Center (50, '-'))

data = F.read () #读取剩下的内容, do not use when the file is large

Print (data) #打印文件

F.close () #关闭文件

The mode of opening a file is as follows:

    • 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.

Python Basic Learning

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.