Python frequently operates on Linux system files and directories

Source: Internet
Author: User
Tags explode locale

Catalog 1, get current directory--OS.GETCWD () >>> import os>>> s=os.getcwd () #获得当前运行脚本所在目录 >>> s ' c:\\python27 ' For example, if you run test.py, entering the command returns the folder location where the script is located. For example, put test.py into the a folder. And you can create a new folder within the A folder, regardless of where you put the a folder on your hard disk. and the name of the folder is automatically generated based on time. >>> Import os>>> Import time>>> folder = Time.strftime (r "%y-%m-%d_%h-%m-%s", Time.localtime ()) >>> os.makedirs (R '%s/%s '% (OS.GETCWD (), folder)) #创建以时间命名文件夹名这是运行脚本的目录即 ' c:\\python27 ' more than one of the folders named at the current time 2 , create subdirectory--os.makedirs ("path"), path is the subdirectory to be created >>> os.makedirs ("C:\\temp\\test") #这是C盘下就创建了temp目录, The nested folder under Temp is test (or, of course, it may fail to create, such as path already exists, or drive is out, or no write permission, etc.) 3, change current directory--os.chdir () equivalent to DOS or Linux CD command >>> Os.chdir (' c:\\ ') #将当前目录改为C盘根目录下4, break the path into directory name and file name--os.path.split () format: fpath, fname = Os.path.split ("Path to explode") >> > A,b=os.path.split ("c:\\dir1\\dir2\\file.txt") >>> print ac:\dir1\dir2>>> print Bfile.txt5, The exploded file name extension--os.path.splitext () is in the format: fpath_name, Ftext = Os.path.splitext ("Path to explode") >>> A,b=os.path.splitext (" C +\dir1\\dir2\\file.txt ") >>> print ac:\dir1\dir2\file>>> print b.txt6, determine if a path (directory or file) exists-- The os.path.exists () format is: os.path.exists ("path or file to be judged") >>> Os.path. Exists ("c:\\") #该路径存在True >>> Os.path . Exists ("c:\\123\\") #该路径不存在False >>> Os.path. Exists ("C:\\123.txt") #该文件不存在False >>> Os.path. Exists ("C:\\Test.txt") #该文件存在True7, determine if a path has the required file--os.path.isfile ("file") >>> Os.path. Isfile ("C:\\Test.txt ") true>>> Os.path. Isfile (" C:\\123.txt ") False8, determine if a path exists--os.path.isdir (" path ") >>> Os.path. Isdir ("c:\\") True>>> Os.path. Isdir ("h:\\") False9, get a list of files and subdirectories in the directory--os.listdir ("path") Equivalent to getting the Get-childitem command in Windows PowerShell and the LS command in Linux. But this display is not in the form of a common list of:>>> Os.listdir ("c:\\") #这里包括隐藏文件也显示出来了 [' $Recycle. Bin ', ' 360ld ', ' 360rescue ', ' 360SANDBOX ', ' 360SysRt ', ' Boot ', ' bootmgr ', ' bootsect. BAK ', ' cachetemp ', ' Documents and Settings ', ' grldr ', ' IFRToolLog.txt ', ' inetpub ', ' MSOCache ', ' Pagefile.sys ', ' program F ' Iles ', ' programFiles (x86) ', ' ProgramData ', ' Python27 ', ' Recovery ', ' recycler ', ' sbtdr ', ' System Volume information ', ' test.txt ', ' Users '  ', ' Windows '] Example: Gets a list of all subdirectories under the specified directory >>> def getdirlist (p): p = str (p) if p== "": Return [] p = p.replace ("/", "\ \") If p[-1]! = "\ \": p = p+ "\ \" a = Os.listdir (p) b = [x for x in a if Os.path.isdir (P + x)] Return b >>> getdirlist ("c:\\") [' $Recycle. Bin ', ' 360rescu E ', ' 360SANDBOX ', ' 360SysRt ', ' Boot ', ' cachetemp ', ' Documents and Settings ', ' inetpub ', ' MSOCache ', ' program Files ', ' Prog Ram Files (x86) ', ' ProgramData ', ' Python27 ', ' Recovery ', ' recycler ', ' System Volume information ', ' Users ', ' Windows '] get the reference List of all files in the directory >>> def getfilelist (p): p = str (p) if p== "": return [] p = p.re Place ("/", "\ \") If p[-1]! = "\ \": p = p+ "\ \" a = Os.listdir (p) b = [x for x in a I F Os.path.isfile (p + x) ] Return b >>> getfilelist ("c:\\") [' 360ld ', ' bootmgr ', ' bootsect. BAK ', ' grldr ', ' IFRToolLog.txt ', ' Pagefile.sys ', ' sbtdr ', ' test.txt ']10, delete subdirectory--os.rmdir ("path"), can only delete empty directories >>> Os.rmdir ("C:\\temp\\test") #注意只删除了test目录 >>> os.rmdir ("c:\\temp") #这里才删除了temp目录 file py The introduction of modules in Thon makes the operation of the file very simple. The most basic file operation is to read and write data in the file, open the file before manipulating the file. Open file--open (' file ' [, ' mode ']) >>>import os>>> os.getcwd () ' c:\\ ' >>> file=open (' Test.txt ') # The default mode is ' R ', that is, read mode >>> file.read () #读取文件内容 ' Hello\nworld\nhello,python ' # \ n the form in the file is the option to wrap mode, meaning the following: modulo Description R Opens the file read-only to read the file information. W writes the file to write information to the file. If the file exists, the file is emptied, the new content is written, and if the file does not exist, create a to open the file in Append mode (that is, an open file, the file pointer is automatically moved to the end of the file), and if the file does not exist, create r+ to open the file in read-write mode. w+ removes the file contents and then opens the file as read-write. A + opens the file in read-write mode and moves the file pointer to the end of the file. b opens the file in binary mode instead of in text mode. This mode is only valid for Windows or DOS, and Unix-like files are operated in binary mode. Other operations on files I don't think it's necessary to record the details, because the basic is very simple, the following list is the common method of the file, and in the example has the relevant description. It is also important to note that the encoding problem is frequently present in the read file. Different interpreters have different default codes, and the specific solution will be introduced. Common file Operation methods: Method Description F.close () Close the file, remember to open the file after opening () mustRemember to close it, otherwise it will take up the number of open file handles of the system. F.name () Gets the file name F.next () returns the next line and shifts the file action marker to the next line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the traversal. F.fileno () Gets the file descriptor, which is a number. Returns a long integer "File label" F.flush () refreshes the output cache, writes the contents of the buffer to the hard disk F.isatty () returns True if the file is a terminal device file (Linux system), otherwise returns false. F.read ([size]) reads the file, size is the length of the read, f.readline ([size]) reads a line of information in byte, and if size is defined, a portion of the line is read out f.readlines ([size]) reads all rows, That is, the information that reads the entire file. (Take each line of the file as a member of a list and return to 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, that is, it may be read only to a portion of the file F.seek (Offset[,where]) moves the file pointer to the offset position relative to where. Where 0 indicates the beginning of the file, this is the default, 1 is the current position, and 2 means the end of the file. (Note: If the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is made) F.tell () Gets the file pointer position, marks the current position, and f.truncate the file to the specified size at the beginning of the file ([size]). The default is where the action tag is cropped to the current file. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add. F.write (String) writes string strings to the file, and write () does not add a newline character after Str. F.writelines (list) writes a string of strings in a list to a file in a row, which is written continuously, with no newline. An existing Test.txt file with the following format: Helloworldhellopython Here are some common operations:>>> file=open (' test.txt ') >>> File.read (4) # Read the first 4 bytes of ' Hell ' >>> file.read (6) #注意这里是在刚才读过的基础上Read back the ' o\nworl ' >>> file.read () #不指定size to the end of the file ' D\nhello\npython ' >>> file.read () #再读时已是文件结尾 ' > >> file.seek (0) #将文件位置定位到第一个字节 >>> file.readline () #一次读一行 ' hello\n ' >>> file.readline () ' world\ N ' >>> file.seek (0) #将文件定位到开始 >>> file.readlines () #读取整个文件的内容 [' hello\n ', ' world\n ', ' hello\n ', ' Pytho N ']>>> file. Tell () #读完之后显示seek位置, which is the final 27L #以长整型表示 >>> file.name #查看文件的名称 ' test.txt ' >>> fi Le.close () #关闭文件 was just beginning to test the use of Read and ReadLine, because as long as it was read once on the basis of the previous reading, then I thought it was a stack operation, obviously, know there is seek this method, I only know it is not, Only the position of seek is shifted one at a time, and each reading is based on the position where seek is located. So if you need to read the file contents from scratch, set the file location to start, which is seek (0). >>> file=open (' Test.txt ', ' W ') >>> file.write (' \nwelcome ') #会将之前的内容覆盖 >>> file.writelines ( ' I love python ') >>> file.close () #关闭文件时才能看到文件内容的修改 >>> file=open (' test.txt ', ' a ') #追加到文件尾 without overwriting >& Gt;> File.writelines (' This is a test ') >>> File.close () related operations to files sometimes need to introduce Shutil modules: >>> Import shutil>>> shutil.copyfile (' test.txt ', ' 123.txt ') #参数只能是文件 >>> shutil.copy ("Olddir", " Newfileordir ") #olddir只能是文件夹, NewFile can be a file, or it can be a target directory >>> shutil.copytree (" Olddir "," Newdir ") # Olddir and Newdir can only be directories, and newdir must not exist >>> Shutil.move ("Oldpos", "Newpos") #移动文件或目录 >>> Shutil.rmtree (" Dir ") #空目录, content directories can be deleted >>> import os>>> os.rmdir (" dir ") #只能删除空目录 >>> os.remove (" file ") #删除文件 & Gt;>> os.rename ("Oldname", "NewName") #文件或目录都是使用这条命令 file Encoding: #获得当前环境默认编码 >>> import sys>>> Import Locale>>> sys.getdefaultencoding () # Returns the default character encoding used by the current system ' ASCII ' >>> sys.getfilesystemencoding () # Returns the encoding used to convert the Unicode file name to the system file name ' MBCS ' >>> Locale.getdefaultlocale () # Gets the default locale and returns the tuple (language, encoding) (' ZH_CN ', ' cp936 ') >>> locale. getpreferredencoding () # Returns the number of files in the user-defined text data encoding ' cp936 ' statistic directory print len ([i[2] for I in Os.walk (path)], []))

Python common use of Linux system files and directories

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.