File input and output in Python and OS module operation on file system

Source: Internet
Author: User

Collated the input and output of the files in Python and mainly describes the operation of the file system in some OS modules.

File input and output

1, built-in function open(file_name,文件打开模式,通用换行符支持) , open file return file object.

2, when the open file to read, readline() the readlines() difference is whether to read all the content one time, and each line of information as a child in the list.
For example: in file Test.txt

  1,3,4  2,35,6

Read them with ReadLine and ReadLines, respectively

r=file_object.readline();#结果为1,3,4r=file_object.readlines();#结果为['1,3,4\n', '2,35,6']

3. File Iteration
Use the iterator's File.next () to read the next line of the file. Compared to the For loop, it is more complex and generally uses a for loop to iterate directly.

4. File movement
seek(off,whence=0)You can move the file pointer in a file to a different location, move the off action marker (file pointer) from the file, and go toward the end, moving in the negative direction. If the whence parameter is set, the starting bit is set to whence, 0 is the starting point, 1 is the current position, and 2 represents the end of the file.
tell()We can show our mobile process and show our current position.

5. OS Module

6. File write F. write() ; writelines() accept a string 列表 as a parameter
You need to enter a newline character manually \ n;

fobj=open('test','w');#直接在指定路径下打开test1 ,如果没有则直接生成,但若存在,则出错;fobj.write('foo\n');fobj.write('bar\n');fobj.close();#结果为#foo#bar
import os;file_object=open(r'E:\Python\iostream_test\test.txt','r+');aline=raw_input("Enter a line ('.'to quit):");if aline !=".":    file_object.write('%s%s' % (aline,os.linesep));#在文件test.txt中写入一条字符串结果为txt 文件中的一个内容
Standard file

When the general program is executed, it is possible to access 3 standard files, namely standard input (usually keyboard), standard output (buffered output to the monitor) and standard error (to the non-buffered output of the screen), where the buffer, non-buffering refers to the three parameters of open ().

File system

Access to file systems is mostly implemented through Python's OS modules. This module is the primary interface for Python to access the functionality of the operating system.

In addition to managing the process and process runtime environment, the OS module handles most of the file system operations , including deleting/renaming files, traversing the directory tree, managing file access, and so on.

Another Os.path module can perform operations on Pathname , which provides functions to manage and manipulate various parts of the file path, to obtain file or subdirectory information, file path queries, and so on.

For OS path operation, manipulate the object E:\Python\iostream_test file and the Test.txt file under it

os.path.exists(), detects whether the file or directory for the specified path exists.

import os;for tempdir in ('/test.txt',r'E:\Python\iostream_test\test.txt'):  if os.path.exists(tempdir):      print 'yes';      break;else:    print 'no temp directory available';    tempdir=' ';#结果为yes,# 若in中改为('/test.txt',r'D:\Python\iostream_test\test.txt'),则结果为no temp directory available

os.path.isdir(), the detection specifies whether the path exists and is a directory, only the directory, or error.

import os;for tempdir in ('/test.txt',r'E:\Python\iostream_test\test.txt'): #in中检测的是文件,而非目录,所以未输出yes  if os.path.isdir(tempdir):      print 'yes';      break;else:    print 'no temp directory available';    tempdir=' ';# 输出no temp directory available
import os;for tempdir in ('/test.txt',r'D:\Python\iostream_test\test.txt'):#指定路径在D盘,因而不存在  if os.path.isdir(tempdir):      print 'yes';      break;else:    print 'no temp directory available';    tempdir=' ';
import os;for tempdir in ('/test.txt',r'E:\Python\iostream_test'): if os.path.isdir(tempdir):     print 'yes';     break;else:   print 'no temp directory available';   tempdir=' ';#输出的是yes

Similarly, you can os.path.isfile() only detect if a specified path exists and is a file

The following exercises for some of the OS, for the operation of the file, because the first detection of the existence of a specified path, and then the path or file in the path to do the operation. More practice can be seen in read.md

Import os;for TempDir in ('/tmp ', R ' E:\Python\iostream_test '): If Os.path.isdir (tempdir): #检测指定路径是否存在且为一个目录, and assign to TempDir      print ' yes ';    Break;else:print ' No temp directory available '; Tempdir= ";" If Tempdir:os.chdir (TempDir); #改变当前工作路径 CWD=OS.GETCWD ();    #获取当前工作路径; print ' Current Temporany directory is: ';    Print CWD;        Print Os.listdir (CWD);    print ' Creating example directory '; Os.mkdir (' example '); #在当前目录下新建一个新的文件 Os.chdir (' example ');    #改变目录到example的文件下 cwd=os.getcwd (); #获取example的文件路径 print ' New working directory: ' Print CWD;    print ' original directory listing: ' Print os.listdir (CWD); #列出 (example) file Os.chdir (tempdir) under the specified path;     CWD=OS.GETCWD (); Print Os.listdir (CWD); #列出 (tempdir) file under specified path # result: # Current Temporany directory is: # e:\python\iostream_test# [' pspathex.py ', ' read.md ', ' read.py ', ' test.txt ']# creating example directory# new working directory:# E:\PYTHON\IOSTREAM_ test\example# Original Directory Listing: # []# [' Example ', ' pspathex.py ', ' read.md ', ' read.py ', ' test.txt '] 

os.path.join()Method combines the separated parts into a path name

 path=os.path.join(cwd,os.listdir(cwd)[0]); print ' full file pathname:' print path; #结果为E:\Python\iostream_test\example\filetest.txt

os.path.split(path)Method divides the combined path (path name, file name)

path=os.path.join(cwd,os.listdir(cwd)[0]);print os.path.split(path);#(pathname,basename)#结果为('E:\\Python\\iostream_test\\example', 'filetest.txt')

os.path.splitext(os.path.basename(path))method to divide the file into (file name, filename extension)

path=os.path.join(cwd,os.listdir(cwd)[0]);print os.path.splitext(os.path.basename(path));#(filename,extension)#结果为('filetest', '.txt')
Related modules

Permanent storage module for permanent storage of data: Pickle, Marshal module, dbm style module, shelve module

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.