python2.7 Getting Started---file (file) &os Files & Directories method

Source: Internet
Author: User

The file object is first created using the Open function, and the following table lists the functions commonly used by the file object:

Serial Number Method and Description
1

File.close ()

Close the file. The file can no longer read and write after closing.

2

File.flush ()

Refreshes the file internal buffer, directly writes the internal buffer data immediately to the file, rather than passively waits for the output buffer to write.

3

File.fileno ()

Returns an integer that is a file descriptor (Descriptor FD Integer) that can be used in some of the underlying operations, such as the Read method of the OS module.

4

File.isatty ()

Returns True if the file is connected to an end device, otherwise False is returned.

5

File.next ()

Returns the next line of the file.

6

File.read ([size])

Reads the specified number of bytes from the file, if none is given or is negative.

7

File.readline ([size])

Reads the entire line, including the "\ n" character.

8

File.readlines ([Sizehint])

Reads all the rows and returns the list, and, given sizeint>0, sets how many bytes are read at a time, in order to alleviate the read pressure.

9

File.seek (offset[, whence])

Set the current location of the file

10

File.tell ()

Returns the current location of the file.

11

File.truncate ([size])

Intercepts the file, the truncated byte is specified by size, and the default is the current file location.

12

File.write (str)

Writes a string to the file without a return value.

13

File.writelines (Sequence)

Writes a list of sequence strings to the file and adds a newline character to each line if a line break is required.

Here are a few tips, first, after the write content, the direct read file output will be empty, because the pointer is already at the end of the content. Two solutions: First, close the file, open and then read, and second, you can set the pointer back to the original file and then read:

#-*-Coding:utf-8-*-ImportOs;Document=Open("Testfile.txt", "W+");Print "File name:",Document.Name;Document.Write("This is the first test file I created!" \nwelcome! "print Document. #输出当前指针位置 document. (os. Seek_set #设置指针回到文件最初 context =. Readprint Context;. Close              

Again, to ensure that the file is closed correctly, whether or not it is an error, we can use the try ... finally to achieve:

try: F = Open ( '/path/to/file ' ,  ' R ' )   F. () finally: if F: F. ()              

But it's so tedious to write every time, so Python introduces a with statement to help us call the close () method automatically:

with open('/path/to/file ',' R ')as f:print f.  Read()             

This is the same as the previous try ... finally, but the code is better and simpler, and you do not have to call the F.close () method.

The next step is the OS. The OS module provides a very rich method for working with files and directories. Common methods are shown in the following table:

Serial Number Method and Description
1

Os.access (path, mode)


Verify permission Mode
2

Os.chdir (PATH)


Change the current working directory
3

Os.chflags (path, flags)


Sets the marker for the path to a numeric marker.
4

Os.chmod (path, mode)


Change permissions
5

Os.chown (path, UID, GID)


Change file Owner
6

Os.chroot (PATH)


Change the root directory of the current process
7

Os.close (FD)


Close File Descriptor FD
8

Os.closerange (Fd_low, Fd_high)


Closes all file descriptors, from Fd_low (inclusive) to Fd_high (not included), and errors are ignored
9

Os.dup (FD)


Copy file Descriptor FD
10

Os.dup2 (FD, FD2)


Copy one file descriptor fd to another FD2
11

Os.fchdir (FD)


Changing the current working directory with file descriptors
12

Os.fchmod (FD, mode)


Change the access permissions for a file, specified by the parameter fd, and the parameter mode is the file access permission under UNIX.
13

Os.fchown (FD, UID, GID)


Modify the ownership of a file, which modifies the user ID and user group ID of a file that is specified by the file descriptor FD.
14

Os.fdatasync (FD)


Forces the file to be written to disk, specified by the file descriptor FD, but does not force the update of the file's state information.
15

Os.fdopen (fd[, mode[, BufSize])


Create a file object with file descriptor FD and return this file object
16

Os.fpathconf (FD, name)


Returns the system configuration information for an open file. Name is the value of the system configuration retrieved, which may be a string that defines system values, which are specified in many criteria (posix.1, UNIX, UNIX 98, and others).
17

Os.fstat (FD)


Returns the state of the file descriptor FD, like stat ().
18

OS.FSTATVFS (FD)


Returns information about the file system that contains file descriptor FD files, such as STATVFS ()
19

Os.fsync (FD)


Forces files with file descriptor FD to be written to the hard disk.
20

Os.ftruncate (fd, length)


Clip file descriptor fd corresponding file, so it cannot exceed the file size maximum.
21st

OS.GETCWD ()


Return to current working directory
22

Os.getcwdu ()


Returns a Unicode object for the current working directory
23

Os.isatty (FD)


Returns true if the file descriptor FD is open while connected to the TTY (-like) device, otherwise false.
24

Os.lchflags (path, flags)


Set the path to a number tag, similar to Chflags (), but no soft link
25

Os.lchmod (path, mode)


Modify Connection File permissions
26

Os.lchown (path, UID, GID)


Changes the file owner, like Chown, but does not track the link.
27

Os.link (SRC, DST)


Create a hard link named DST, point to parameter src
28

Os.listdir (PATH)


Returns a list of the names of files or folders contained in the folder specified by path.
29

Os.lseek (FD, POS, how)


Set file descriptor fd Current position is POS, how mode modified: Seek_set or 0 sets the computed POS starting from the file; Seek_cur or 1 is calculated from the current position; Os. Seek_end or 2 starts at the end of the file. Effective in Unix,windows
30

Os.lstat (PATH)


Like stat (), but no soft links
31

Os.major (device)


Extract the device major number from the original device number (using St_dev in stat or St_rdev field).
32

Os.makedev (major, minor)


Make an original device number with the major and minor device numbers
33

Os.makedirs (path[, mode])


Recursive folder creation functions. Like MkDir (), but all Intermediate-level folders that are created need to contain subfolders.
34

Os.minor (device)


Extract the device minor number from the original device number (using St_dev in stat or St_rdev field).
35

Os.mkdir (path[, mode])


Create a folder named path in the digital mode mode. The default mode is 0777 (octal).
36

Os.mkfifo (path[, mode])


Create a named pipe, mode is a number, default is 0666 (octal)
37

Os.mknod (filename[, mode=0600, device])
Create a system node named filename file (file, device special file, or named pipe).

38

Os.open (file, flags[, mode])


Open a file and set the required open options, the mode parameter is optional
39

Os.openpty ()


Open a new pseudo-terminal pair. Returns the file descriptor for the Pty and TTY.
40

os.pathconf (path, name)


Returns system configuration information for the related file.
41

Os.pipe ()


Create a pipeline. Returns a pair of file descriptors (R, W), respectively, for read and write
42

Os.popen (command[, mode[, BufSize])


Open a pipe from a command
43

Os.read (FD, N)


Reads up to n bytes from the file descriptor fd, returns a string containing the read bytes, and the file descriptor fd corresponding file has reached the end, returning an empty string.
44

Os.readlink (PATH)


Returns the file that the soft link points to
45

Os.remove (PATH)


Deletes a file with path. If path is a folder, it will throw oserror; View the following rmdir () to remove a directory.
46

Os.removedirs (PATH)


recursively deletes the directory.
47

Os.rename (SRC, DST)


Rename a file or directory, from SRC to DST
48

Os.renames (old, new)


Rename the directory recursively, or rename the file accordingly.
49

Os.rmdir (PATH)


Deletes the empty directory specified by path and throws a OSError exception if the directory is not empty.
50

Os.stat (PATH)


Gets the information for the path specified by path, which is equivalent to the stat () system call in the C API.
51

Os.stat_float_times ([newvalue])
Determines whether Stat_result displays timestamps as float objects

52

OS.STATVFS (PATH)


Gets file system statistics for the specified path
53

Os.symlink (SRC, DST)


Create a soft link
54

OS.TCGETPGRP (FD)


Returns the process group associated with Terminal FD (an open file descriptor returned by Os.open ())
55

OS.TCSETPGRP (FD, PG)


Sets the process group associated with Terminal FD (an open file descriptor returned by Os.open ()) to pg.
56

Os.tempnam ([dir[, prefix]])


Returns a unique path name used to create a temporary file.
57

Os.tmpfile ()


Returns a file object with an open mode of (W+B). This file object has no folder entry, no file descriptor, and will be automatically deleted.
58

Os.tmpnam ()


Returns a unique path for creating a temporary file
59

Os.ttyname (FD)


Returns a String that represents the terminal device associated with the file descriptor FD. If the FD is not associated with the end device, an exception is thrown.
60

Os.unlink (PATH)


Delete file path
61

Os.utime (path, times)


Returns the time that the specified path file was accessed and modified.
62

Os.walk (top[, topdown=true[, onerror=none[, Followlinks=false]])


Output the file name in the folder by walking in the tree, up or down.
63

Os.write (FD, str)


Writes a string to the file descriptor FD. Returns the string length actually written

Reference Address: http://kuanghy.github.io/python-os/http://python.usyiyi.cn/python_278/library/os.html

Well, here's what this article says. If you feel good, please more praise support oh ...

Original link: 79976351

python2.7 Getting Started---file (file) &os Files & Directories method

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.