Python: File operations

Source: Internet
Author: User

First, File open mode

Format: Open (file, mode = ' r ', buffering =-1, encoding = none, errors = none, newline = none, Closefd = True, open = none)

==> general commonly used file, mode two parameters;

#file: The address of the opened file + file name, if only the file name, the file is opened in the current directory (the regular execution of the. py file all folders); The default location is current;

#mode: File open mode;

mode take action
opens the file as read-only (default); #若文件不存在, report exception, not new;
' W ' Create a new file in writing; #若文件名存在, overwrite it;
new file; #如果文件存在, throws an exception;
' a '   Open the file as written, #若文件存在 to append the content after the file, and if the file does not exist, create a new file;
' B ' open file in binary mode, #如 ' RB ', ' WB ', ' AB ', ' xb ', etc.
Open file in text mode (default);
"+" K read-write mode; (to be used in other modes)
' U ' Universal line break support

f = open ('Test.txt','W') s='This boy is so handsome .'F.write (s) F.closef= Open ('Test.txt')Print(Type (f))#output: <class ' _io. Textiowrapper ' >#_io. Textiowrapper: What does that mean? Print(List (f))#output: [' This boy is so handsome ']
Ii. Methods of File objects
Methods for File objects Perform actions Syntax format
Close () Close the file; F.close ()
Read (size =-1)

a size character (not a byte)is read from a file, and if a size value is not given or a negative value is

Reads the remaining (from the file pointer position) all bytes and then returns as a string;

F.read (n):

Reads n bytes from the position of a pointer

ReadLine () Reads a whole line of string starting from the position of the file pointer, #一整行: Branch with line feed ' \ n '; F.read ()
Write (str) Writes a string to a file; #所写入的数据必须是字符串; F.write (' string ')
Writelines (Sep) Writes a string sequence to a file Sep; #sep是一个返回字符串的可迭代对象, not the string itself; F.writelines (an iterative object of a string)
Seek (offset, from)

Move a file pointer; #从offset (0/1/2), offset from bytes;

#0代表文件起始位置; 1 represents the current position of the pointer; 2 represents the end of the file;

#from为具体的正整数;

F.seek (1, size):

#从当前指针位置移动size个字节;

Tell () Returns the current position of the pointer, #结果为正整数, indicating the number of bytes of the pointer from the beginning of the file; F.tell ()

#文件指针: The equivalent of a ' bookmark ', when the file is cited, read, write, from the pointer position to start operation;

#一个字符是1个字节; a Chinese character is 2 bytes;

#文件本身可以看做是一个字符串, when reading a file, returns a file object, which can be iterated, as with a string iteration;

f = open ('test.txt'w') for in F:     Print (i) # output: This boy is so handsome .

Third, Python file system method 1) functions in the OS module about files/directories

#对于文件系统的访问, Python is generally implemented through the OS module;

#Python是夸平台的语言: When the same source code is executed on different operating systems, no modification is required;

#OS: System module; (Operating systems)

#使用OS模块下的方法前, first import the OS module: Import os

Functions in the OS module about files/directories

Name of function Function Syntax format
GETCWD () Returns the current working directory; #即当前工作的物理地址 OS.GETCWD ()
ChDir (PATH) Change the working directory; #path指代需要切换到的目录 Os.chdir (PATH)
Listdir (Path = '. ')

L LIST the name of the file in the specified directory (including the name of the folder), where the file name is formatted (such as '. Py ', '. txt ') and returned in [' str1 ', ' str2 '] form;

#‘.‘ : Indicates the current working directory, which is also the default value; # ' ... ' : Represents the previous level of the working directory;

#path指定具体地址, such as (' E:\PYTHONWJ '): Returns the file name under the specified address;

Os.listdir (Path = '. ')
mkdir () In the current working directory, create a single folder (not a file); #如果文件夹已存在, throw an exception; Os.mkdir ()
Makedirs (PATH)

Create multi-level folders under the specified directory; #如果文件夹已存在, throw exceptions;

#例1: Os.makedirs (R ' \a\b\c '): A in the current working directory, b under the A folder, C under the B folder;

#r '. \a\b\c ': To add r, to represent the original string, or to add '. \ ' If created under the current working directory;

#例2: Os.makedirs (R ' E:\pythonwj\a\b\c ')

Os.makedirs (PATH)

Remove (PATH) Deletes the file specified under the current working directory; #不是文件夹 Os.remove (PATH)
RmDir (PATH) Deletes the specified single-level folder under the current working directory; #文件下不在有其它文件; Os.rmdir (PATH)
Removedirs (PATH)

Deletes the specified multi-tier file under the current working directory; #连同文件夹下的其它文件夹同时删除;

#os. Removedirs (R ' a\b\c '): Delete the A folder under the current working directory, and the B and C folders under the A folder;

Os.removedirs (PATH)
Rename ()

Renames the folder or file under the current working directory;

#os. Rename (' filename 1/folder name 1 ', ' File name 2/folder name 2 '):

==> file 1/Folder 1 in the current directory, renamed to file 2/folder 2

Os.rename (name1,name2)
System ()

s use of system gadgets;

#例: Os.system (' calc '): Turn on the system's calculator;

Os.system (' Gadget code ')
Walk (top)

Traverse the top parameter to specify all subdirectories under the path and return the result to a ternary group (path, [include directory], [include file])

#top: The path of the top-level directory that needs to traverse;

Os.walk (top)

Extensions :

Os.curdir indicates the current directory ('. ') ;

Os.pardir indicates the previous level of directory (' ... ') ;

OS.SEP represents the delimiter for the path, such as ' \ \ ' under the Windows system and '/' under the Linux system;

OS.LINESEP represents the line in the current platform, ("\ r \ n" under Windows, "\ n" under Linux)

Os.name indicates the operating system currently in use;

Import OS Print (OS.SEP) # output: \

#walk (top) usage, and the difference from Os.path.walk (), see: Python:os.walk () and Os.path.walk () usage

Instance:

ImportOS forIinchOs.walk (R'E:\PYTHONWJ'):    Print(i)#Output:# (' e:\\pythonwj ', [' chapter_2 ', ' chapter_3 ', ' chapter_4 ', ' chapter_5 ', ' chapter_6 '], [])#(' e:\\pythonwj\\chapter_2 ', [], [' 0_0.py ', ' 2_1.py ', ' 2_2.py ', ' 2_3.py '])#(' e:\\pythonwj\\chapter_3 ', [], [' 0-0.py ', ' 3-1.py ', ' 3-3-1.py ', ' 3-3-2.py ', ' 3-4.py ', ' 3-5.py '])#(' e:\\pythonwj\\chapter_4 ', [], [' 0-0.py ', ' 0.py ', ' 00.py ', ' 4-1.py ', ' 4-2.py ', ' 4-4.py ', ' 4-5.py ', ' 4-6.py ', ' Recor ' D.txt ', ' test.txt ', ' test_1.txt ', ' test_2.txt ', ' test_3.txt ', ' txt ' test_2.txt ', ' test_3.txt ', ' txt.py ']#(' e:\\pythonwj\\chapter_5 ', [], [])#(' e:\\pythonwj\\chapter_6 ', [], [])
(ii) functions commonly used in the Os.path module on paths
functions common to paths in Os.path modules
Name of function function and how to use
basename (PATH) Remove directory path, return file name separately
DirName (PATH) Remove the file name and return the directory path separately;
Join (path1[, path2[, ...]) Combine parts of path1 and path2 into one path name
Split (PATH)

Split file name and path, return (F_path, f_name) tuple;

#如果完全使用目录, it also separates the last directory as the file name, and does not determine whether the file or directory exists;

Splitext (PATH) Detach the file name and extension, and return (F_name, f_extension) tuples;
GetSize (file) Returns the size of the specified file, in bytes;
Getatime (file) Returns the time of the most recent access to the specified file: floating-point number of seconds, (Gmtime () or localtime () function conversion of a time module can be used)
Getctime (file) Returns the creation time of the specified file: floating-point number of seconds, (Gmtime () or localtime () function conversion of time module available)
Getmtime (file) Returns the latest modification time for the specified file: floating-point number of seconds, (Gmtime () or localtime () function conversion of the time module available)

The following function returns TRUE or FALSE

Name of function Function and use method
Exists (PATH) Determines whether the specified path (directory or file) exists
Isabs (PATH) Determines whether the specified path is an absolute path
Iadir (PATH) Determine if the specified path exists and is a directory
Iafile (PATH) Determines whether the specified path exists and is a file
Islink (PATH) Determines whether the specified path exists and is a symbolic link
Ismount (PATH) Determines whether the specified path exists and is a mount character
Samefile (path1, path2) Determine if the two paths of path1 and path2 point to the same file

Python: 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.