Python-based file operations

Source: Internet
Author: User

There are many types of file operations

Here we can roughly divide, the operation of the file can be divided into the overall operation of the file ( create files, delete files, rename files, get file attributes ) and the contents of the file operation ( modify the contents of the file)

Let's look at the overall operation of the file:

We are in accordance with the order of additions and deletions to tell

1 increase

The so-called increase, that is new.

Create a new file

F=open ('lalal','w+')    #如果该文件 (Lalal) does not exist and is created if it exists.

Create a new directory:

>>> Os.listdir () ['log'test1'] >>> os.mkdir ('bin')>>> os.listdir () ['  log'bin'test1 ' ]

2 by deleting

The so-called deletion, namely delete.

To delete a file:

>>>ImportOS>>>Os.listdir () ['Log','Test','bin','test1']>>> Os.remove ('Test' #仅仅只能删除文件, if you delete the directory, you will get an error. >>>Os.listdir () ['Log','bin','test1']

To delete a directory:

>>> os.rmdir ('bin')>>> os.listdir () ['  log'test1']

3 Check

View the various properties of the file, such as the file that is contained in the directory, create time to modify the time to access the file permissions file size ...

To view the files and directories contained in the directory:

>>> Os.listdir () ['log''bin'  test1']

Get File/directory information:

>>> os.stat ('test1') os.stat_result (St_mode=33188, st_ino=137156, St_ dev=2050, St_nlink=1, St_uid=0, St_gid=0, st_size=0, st_atime=1463225144, st_mtime=1463225144, st_ctime=1463225144)

4 Change

To modify permissions for a file/directory:

>>> Os.stat ('test1') Os.stat_result (St_mode=33188, st_ino=137156, st_dev=2050, St_nlink=1, St_uid=0, St_gid=0, st_size=0, st_atime=1463225144, st_mtime= 1463225144, st_ctime=1463225144)>>> Os.chmod ('test1', 3)           >>> Os.stat ('test1') Os.stat_result (St_mode=32771, st_ino=137156, st_dev=2050, St_nlink=1, St_uid=0, St_gid=0, st_size=0, st_atime=1463225144, st_mtime= 1463225144, st_ctime=1463225965) [[email protected] python_test]#LSATotal 16drwxr-xr-x. 4 root root 4096 May 14 04:31. Dr-xr-x---. 5 root root 4096 May 14 04:25 .. DRWXR-xr-x. 2 root root 4096 May 14 04:31BINDRWXR-xr-x. 2 root root 4096 May 14 04:25Log-rw-r--r--. 1 root root 0 May 14 04:25Test1[[email protected] python_test]#LSATotal 16drwxr-xr-x. 4 root root 4096 May 14 04:31. Dr-xr-x---. 5 root root 4096 May 14 04:25 .. DRWXR-xr-x. 2 root root 4096 May 14 04:31BINDRWXR-xr-x. 2 root root 4096 May 14 04:25Log--------WX. 1 root root 0 may 04:25 test1
View Code

Modify file contents (read and write files)

Before reading and writing files, we must first understand that the ability to read and write files on disk is provided by the operating system, the modern operating system does not allow ordinary programs to operate the disk directly, so the read-write file is to request the operating system to open a file object (often referred to as a file descriptor), and then, Read the data from this file object (read the file) from the interface provided by the operating system, or write the data to the file object (write file).

So if you want to read or write a file, you need to open the file first.

How to open it?

[[email protected] python_test] #  Helloworld >>> f=open ('test1','R ')     # Open File
#格式open (' file ', mode)
File: Files
Mode

w      Open as write,
a      opens in Append mode (starting with EOF and creating a new file if necessary)
r+      open in read-write mode
w+      open in read-write mode (see W)
a+      open in read-write mode (see a)
rb      Open the
wb       opens in binary write mode (see W)
ab      opens in binary append mode (see a)
rb+     opens in binary read-write mode (see r+)
wb+     open in binary read-write mode (see w+)
ab+      Open in binary read/write mode (see A +)

How to read a file

Fp.read ([size]) #size为读取的长度, in bytes

Fp.readline ([size]) #读一行, if size is defined, it is possible to return only part of a row

Fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns the list. In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter #数, size is the total length of the read content, which means that it may be read only to a portion of the file.

[[email protected] python_test]#Cat Test1Hello worldmy name isLimingi LiveinchShijiazhuanga City notFar fromBeijing>>> F=open ('test1','R')>>>F.read ()'Hello world\nmy name is Liming\ni live in shijiazhuang\na City no far from beijing\n'>>> F=open ('test1','R')>>>F.readline ()'Hello world\n'>>> F=open ('test1','R')>>>f.readlines () ['Hello world\n','My name is liming\n','I live in shijiazhuang\n','a city is far from beijing\n']


How do I write a file?

Fp.write (str) #把str写到文件中, write () does not add a newline character after Str

Fp.writelines (seq) #把seq的内容全部写到文件中 (Multi-line write-once). This function simply writes faithfully and does not add anything behind each line.

>>> F=open ('test1','w+')>>>F.read ()"'      #when a file is opened as written, the original content of the file does not exist.>>> sentence=["everbody 'll make mistakes\n","That's why they put erasers on the end of pencils.\n"]>>>f.writelines (sentence)>>>f.readlines () []#even if the content is written, the new content is still not visible. >>>f.close ()>>> F=open ('test1','R')>>>F.read ()"Everbody would make Mistakes\nthat's why they put erasers on the end of pencils.\n"

Python-based file operations

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.