Python's File object

Source: Internet
Author: User
Tags ticket dovecot

Security code Forget the Childe


The file object is used to access the data corresponding to the file system interface.

A file system is the method and data structure used by the OS to clear files on a disk or partition-the method of organizing files on disk

Computer file or file, computer files, files are a stream of data stored in a long-term storage device or temporary storage device and belong to the computer file system management

Broadly speaking

A file is a name-controlled storage area of the computer that is managed by the OS

A file is considered a byte sequence on a Linux system.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/8B/AF/wKiom1hU9w-jYLj5AAC2K7fvLZ8039.png "title=" File stream. png "alt=" Wkiom1hu9w-jylj5aac2k7fvlz8039.png "/>


One of the prerequisites for storing data in a file is that you must serialize non-serialized data that is not simply stored in a file in the file system.


For Python, file objects can be used not only to access normal disk files, but also some special files in Linux, such as socket files, named pipes, and so on, can be accessed through the object interface of the file.


Python's built-in function open () is used to implement the creation of a file object.

Python's built-in function open () Opens the file and creates the file object using the following method

Open (name [, mode [, BufSize]])

The open function can receive three parameter filenames, patterns, and buffer parameters. The open function returns a file object

Mode to specify the opening modes of the file

Simple mode

R Read-only

W Write

A plus

Use "+" after pattern to support input and output operations at the same time

r+

w+

A +

Append "B" to the pattern to open in binary mode

such as RB, wb+

When a file is opened in writable mode, the file is created if it does not exist

An exception is emitted when a file is opened in read-only mode if the file does not exist

BufSize Defining output Caching

0 indicates no output cache disable buffering

1 means buffering only one row of data using buffering

A negative number means that the system default buffering is used with system default settings

A positive number indicates the buffer space size is specified using a buffer of approximately the specified size


Methods for File objects

The File.next () method iterates through all the rows of a file

In [1]: f = open ('/etc/passwd ') in [2]: f.next () out[2]:  ' ##\n ' In [3]:  f.next () out[3]:  ' # user database\n ' In [4]: f.next () Out[4]:  ' # \n ' in  [5]: f.next () out[5]:  ' # note that this file is consulted  Directly only when the system is running\n ' In [6]: f.next () Out[6]:   ' # in single-user mode.  at other times this information  is provided by\n ' In [7]: f.next () out[7]:  ' # open directory.\n ' in  [8]: f.next () out[8]:  ' #\n ' In [9]: f.next () out[9]:  ' # See the  Opendirectoryd (8)  man page for additional information about\n ' In [10]:  f.next () out[10]:  ' # open directory.\n ' In [11]: f.next () Out[11]:  ' ##\n ' in  [12]: f.next () out[12]: ‘ Nobody:*:-2:-2:unprivileged user:/var/empty:/usr/bin/false\n ' In [13]: f.next () Out[13]:  ' Root:*:0:0:system administrator:/var/root:/bin/sh\n ' In [14]: f.next () Out[14]:  ' daemon:* : 1:1:system services:/var/root:/usr/bin/false\n ' In [15]: f.next () Out[15]:  ' _uucp:*:4:4: Unix to unix copy protocol:/var/spool/uucp:/usr/sbin/uucico\n '


The File.close () method closes a file that is closed and no longer reads data from it

in [+]: F.close () in [+]: F.next ()--------------------------------------------------------------------------- ValueError Traceback (most recent) <ipython-input-25-c3e65e5362fb> in <mo Dule> ()----> 1 f.next () valueerror:i/o operation on closed file


The File.fileno () method returns the file descriptor of the file object

in [+]: F = open ('/etc/passwd ') in []: F.fileno () out[28]: 10


File.readline () method executes one row at a time

in [+]: F = open ('/etc/passwd ') in [to]: F.readline () out[31]: ' ##\n ' in [+]: F.readline () out[32]: ' # User database\n ' in [3 3]: F.readline () out[33]: ' # \ n '


File.readlines () method returns all rows of a file in list mode

In [34]: f = open ('/etc/passwd ') in [35]: f.readlines () Out[35]:[' ##\n ',  ' #  user database\n ',  ' # \n ',  ' # note that this file is  consulted directly only when the system is running\n ',  ' # in  single-user mode.  At other times this information is  provided by\n ',  ' # open directory.\n ',  ' #\n ',  ' # see the  Opendirectoryd (8)  man page for additional information about\n ',  ' #  open directory.\n ',  ' ##\n ',  ' nobody:*:-2:-2:unprivileged user:/var/empty:/usr/bin/false\n ' ,  ' root:*:0:0:system administrator:/var/root:/bin/sh\n ',  ' daemon:*:1:1:system services:/ var/root:/usr/bin/false\n ',  ' _uucp:*:4:4:unix to unix copy protocol:/var/spool/uucp:/ usr/sbin/uucico\n ',  ' _taskgated:*:13:13:task gate daemon:/var/empty:/usr/bin/false\n ',  ' _networkd:*:24:24:network services :/var/networkd:/usr/bin/false\n ',  ' _installassistant:*:25:25:install assistant:/var/empty:/usr/bin/ false\n ',  ' _lp:*:26:26:printing services:/var/spool/cups:/usr/bin/false\n ',  ' _postfix:*:27:27: postfix mail server:/var/spool/postfix:/usr/bin/false\n ',  ' _scsd:*:31:31:service  configuration service:/var/empty:/usr/bin/false\n ',  ' _ces:*:32:32:certificate enrollment  service:/var/empty:/usr/bin/false\n ',  ' _mcxalr:*:54:54:mcx applaunch:/var/empty:/usr/bin/false\n ',   ' _appleevents:*:55:55:appleevents daemon:/var/empty:/usr/bin/false\n ',  ' _geod:*:56:56:Geo  services daemon:/var/db/geod:/usr/bin/false\n ',  ' _serialnumberd:*:58:58:serial number  daemon:/var/empty:/usr/bin/false\n ',  ' _devdocs:*:59:59:developer documentation:/var/empty:/usr /bin/false\n ',  ' _sandbox:*:60:60:seatbelt:/var/empty:/usr/bin/false\n ',  ' _mdnsresponder:*:65:65:mdnsresponder:/var/empty:/usr/bin/ false\n ',  ' _ard:*:67:67:apple remote desktop:/var/empty:/usr/bin/false\n ',  ' _www:*:70:70: world wide web server:/library/webserver:/usr/bin/false\n ',  ' _eppc:*:71:71:Apple  events user:/var/empty:/usr/bin/false\n ',  ' _cvs:*:72:72:cvs server:/var/empty:/usr/bin/false\n ' ,  ' _svn:*:73:73:svn server:/var/empty:/usr/bin/false\n ',  ' _mysql:*:74:74:mysql server:/var /empty:/usr/bin/false\n ',  ' _sshd:*:75:75:sshd privilege separation:/var/empty:/usr/bin/false\n ' ,  ' _qtss:*:76:76:quicktime streaming server:/var/empty:/usr/bin/false\n ',  ' _cyrus:*:77:6: cyrus administrator:/var/imap:/usr/bin/false\n ',  ' _mailman:*:78:78:mailman list server:/ var/empty:/usr/bin/false\n ',  ' _appserver:*:79:79:application server:/var/empty:/usr/bin/false\n ',   ' _clamav:*:82:82:clamav daemon:/var/virusmails:/usr/bin/false\n ',  ' _amavisd:*:83:83:amavis daemon:/var/virusmails :/usr/bin/false\n ',  ' _jabber:*:84:84:jabber xmpp server:/var/empty:/usr/bin/false\n ',  ' _ appowner:*:87:87:application owner:/var/empty:/usr/bin/false\n ',  ' _windowserver:*:88:88:windowserver :/var/empty:/usr/bin/false\n ',  ' _spotlight:*:89:89:spotlight:/var/empty:/usr/bin/false\n ',  ' _tokend: *:91:91:token daemon:/var/empty:/usr/bin/false\n ',  ' _securityagent:*:92:92:securityagent:/var/db/ securityagent:/usr/bin/false\n ',  ' _calendar:*:93:93:calendar:/var/empty:/usr/bin/false\n ',  ' _ teamsserver:*:94:94:teamsserver:/var/teamsserver:/usr/bin/false\n ',  ' _update_sharing:*:95:-2:update  sharing:/var/empty:/usr/bin/false\n ',  ' _installer:*:96:-2:installer:/var/empty:/usr/bin/false\n ',  ' _ atsserver:*:97:97:ats server:/var/empty:/usr/bin/false\n ',  ' _ftp:*:98:-2:ftp daemon:/var/empty :/usr/bin/false\n ', &nbsP; ' _unknown:*:99:99:unknown user:/var/empty:/usr/bin/false\n ',  ' _softwareupdate:*:200:200:software  update service:/var/empty:/usr/bin/false\n ',  ' _coreaudiod:*:202:202:core audio  daemon:/var/empty:/usr/bin/false\n ',  ' _screensaver:*:203:203:screensaver:/var/empty:/usr/bin/false\n ',   ' _locationd:*:205:205:location daemon:/var/db/locationd:/usr/bin/false\n ',  ' _ trustevaluationagent:*:208:208:trust evaluation agent:/var/empty:/usr/bin/false\n ',  ' _timezone: *:210:210:autotimezonedaemon:/var/empty:/usr/bin/false\n ',  ' _lda:*:211:211:local delivery agent :/var/empty:/usr/bin/false\n ',  ' _cvmsroot:*:212:212:cvms root:/var/empty:/usr/bin/false\n ',  ' _ usbmuxd:*:213:213:iphone os device helper:/var/db/lockdown:/usr/bin/false\n ',  ' _dovecot:* : 214:6:dovecot administrator:/var/empty:/usr/bin/false\n ',  ' _dpaudio:*:215:215:dp audio:/var/ empty:/usr/bin/false\n ',  ' _postgres:*:216:216:postgresql server:/var/empty:/usr/bin/false\n ',  ' _krbtgt:*:217:-2:kerberos ticket  granting ticket:/var/empty:/usr/bin/false\n ',  ' _kadmin_admin:*:218:-2:kerberos admin  service:/var/empty:/usr/bin/false\n ',  ' _kadmin_changepw:*:219:-2:kerberos change password  service:/var/empty:/usr/bin/false\n ',  ' _devicemgr:*:220:220:device management server:/var /empty:/usr/bin/false\n ',  ' _webauthserver:*:221:221:web auth server:/var/empty:/usr/bin/false\n ',  ' _netbios:*:222:222:netbios:/var/empty:/usr/bin/false\n ',  ' _warmd:*:224:224:warm daemon:/var /empty:/usr/bin/false\n ',  ' _dovenull:*:227:227:dovecot authentication:/var/empty:/usr/bin/false\n ',   ' _netstatistics:*:228:228:network statistics daemon:/var/empty:/usr/bin/false\n ',  ' _ avbdeviced:*:229:-2:ethernet avb device daemon:/var/empty:/usr/bin/false\n ',  ' _krb_krbtgt: *:230:-2:open directory kerberos ticket granting ticket:/var/empty:/usr/bin/false\n ',  ' _krb_kadmin:*:231: -2:open directory kerberos admin service:/var/empty:/usr/bin/false\n ',  ' _KRB_CHANGEPW :*: 232:-2:open directory kerberos change password service:/var/empty:/usr/bin/false\n ',  ' _krb_kerberos:*:233:-2:open directory kerberos:/var/empty:/usr/bin/false\n ',  ' _krb_ Anonymous:*:234:-2:open directory kerberos anonymous:/var/empty:/usr/bin/false\n ',  ' _ assetcache:*:235:235:asset cache service:/var/empty:/usr/bin/false\n ',  ' _coremediaiod:*:236:236 : core media io daemon:/var/empty:/usr/bin/false\n ',  ' _launchservicesd:*:239:239:_ launchservicesd:/var/empty:/usr/bin/false\n ',  ' _iconservices:*:240:240:iconservices:/var/empty:/usr/bin/ false\n ',  ' _distnote:*:241:241:distnote:/var/empty:/usr/bin/false\n ',  ' _nsurlsessiond:*:242:242: nsurlsession daemon:/var/db/nsurlsessiond:/usr/bin/false\n ',  ' _nsurlstoraged:*:243:243:nsurlstorage daemon:/var/empty:/usr/bin/ false\n ',  ' _displaypolicyd:*:244:244:display policy daemon:/var/empty:/usr/bin/false\n ',  ' _astris:*:245:245:astris services:/var/db/astris:/usr/bin/false\n ',  ' _krbfast:*:246:-2:Kerberos  fast account:/var/empty:/usr/bin/false\n ',  ' _gamecontrollerd:*:247:247:game controller  daemon:/var/empty:/usr/bin/false\n ',  ' _mbsetupuser:*:248:248:setup user:/var/setup:/bin/bash\n ',  ' _ondemand:*:249:249:on demand resource daemon:/var/db/ondemand:/usr/bin/false\n ',   ' _xserverdocs:*:251:251:os x server documents service:/var/empty:/usr/bin/false\n ',   ' _wwwproxy:*:252:252:www proxy:/var/empty:/usr/bin/false\n ']

Since ReadLines is a one-time fetch of all rows if the file data is particularly numerous will be extremely memory-intensive, so generally not readlines if you need to read a file all rows can be iterated using ReadLine

An empty string is returned when ReadLine executes ReadLine when it reads to the end of the file

In [1]: F = open ('/users/seancheng/aa.txt ') in [2]: F.readline () out[2]: ' fadjlfjdakf\n ' in [3]: F.readline () out[3]: ' 213242345\n ' in [4]: F.readline () out[4]: ' fjdagu8908fa\n ' in [5]: F.readline () out[5]: ' fdaf343435\n ' in [6]: F.readline () OUT[6]: ' fadgjljl;8\ n ' in [7]: F.readline () out[7]: ' fjadljg5\n ' in [8]: F.readline () out[8]: "In [9]: F.readline () out[9]: '


The File.tell () method returns the position of the current pointer in the file. In bytes, this indicates that the pointer is in the position of the 66th byte

In [ten]: F.tell () out[10]: 66


The File.seek () method defines the location of the file pointer using the following method

Seek (offset[, whence])

Offset specify offsets

Whence specify where to start the offset

0 indicates starting offset from file header

1 indicates offset from current position

2 means offset from end of file

in [+]: F.tell () out[13]: 66In []: F.seek (0) in [All]: F.tell () out[15]: 0

As shown above, if you do not give whence, the default start offset from the file header


The File.read () method explicitly specifies how many bytes of data to read from the file are returned as a string

Example reads 10 bytes

in [+]: F.read (Ten) out[16]: ' Fadjlfjdak ' in [+]: F.tell () out[17]: 10

The entire file is read when the number of bytes is not specified

In [1]: F = open ('/users/seancheng/aa.txt ') in [2]: F.tell () out[2]: 0In [3]: F.read () out[3]: ' Fadjlfjdakf\n213242345\ Nfjdagu8908fa\nfdaf343435\nfadgjljl;8\ Nfjadljg5\n ' in [4]: F.tell () Out[4]: 66


File.name property calls the full path name of the current file directly

In [6]: f.nameout[6]: '/users/seancheng/aa.txt '


File.write (s) write String s

File.writelines (lines) writes all strings in a sequence lines can only write string sequences to a file

File.flush () Flush buffer manually synchronizing data to disk

File.truncate ([size]) truncates the file to a maximum size byte, which means that only the size byte is left after the file is intercepted

File.closed returns whether the current file is in a closed state

File.encoding returns the encoding used for the current file

File.mode returns the open mode of the current file


This is the file object in Python that is only used as a learning growth record for python.

This article from "Indifferent bo" blog, please be sure to keep this source http://itchentao.blog.51cto.com/5168625/1883617

Python's File object

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.