python core programming: read and write files and directories of files python and the operation of the implementation code folder

This article focuses on the reading and writing of files and file directory folder and the operation of the python implementation code, need a friend at the reference
For security reasons, it is best to open the file object to specify a name, so that at the completion of the operation you can quickly close the file, preventing some useless objects occupy memory file. For example, the reading of the text file:

file_object = open('thefile.txt') 
try: 
all_the_text = file_object.read( ) 
finally: 
file_object.close( )

Step Five Python file read and write operations actual

First, open the file

Python reading and writing files are widely used in computer languages, if you want to understand the application procedure, the following article will give you a detailed introduction to related content, will help you in the process of learning in the future, here we come details of its application.
Code as follows: f = open("d:\test.txt", "w")
Description:
The first argument is the file name, including the path; a second parameter is the open mode MODE
'R & lt': read-only (default if the file does not exist, an error is thrown.)
'W': Only write (if the file does not exist, create a file)
'A': appended to the file
'r +': the reader
if required to open the file in a binary manner, the need to add the character "b" mODE later, such as "rb" " wb ", etc.

Second, read the contents

reached, f.read (size)
Number size parameter indicates the read, it can be omitted. If you omit the size parameter, then read all the contents of the file.
f.readline ()
to read the file line content
f.readlines ()
to read all of the rows in the array which [line1, line2, ... lineN] . Avoid loading the contents of all files in memory, this method is often used to facilitate improved efficiency.

Third, write to the file

f.write (string)
to a string to the file, if the write end, must be added "\ n" at the end of the string, and then f.close () closes the file

Fourth, the contents of the file location

f.read ()
after reading the file pointer reaches the end of the file, if again f.read () will find that reading the content is empty, if you want to read the entire contents again, you must locate the file pointer to the beginning :
f.seek (0)
the format of this function is as follows (in units of bytes):
f.seek (offset, a from_what)
a from_what indicates the position to start reading, offset indicates an amount of movement and from a distance from_what, such f.seek ( 10, 3) represents a third character is positioned to move back and then 10 characters. from_what value of 0 indicates start of the file, it may be omitted, the default is 0, document beginning. Given below

f = open('/tmp/workfile', 'r+') 
f.write('0123456789abcdef') 
f.seek(5) # Go to the 6th byte in the file 
f.read(1)  
'5'
f.seek (-3, 2) # Go to the 3rd byte before the end 
f.read(1) 
'd'

We recommend the python learning sites to see how seniors are learning! From basic python script, reptiles, django, data mining, programming techniques, as well as to combat zero-based sorting data items, given to every love learning python small partner! Python veteran day have to explain the timing of technology, to share some of the ways to learn and need to pay attention to small details, click on Join us python learner gathering

Fifth, close the file release resources

File operation is completed, we must remember to close the file f.close (), you can free up resources for other programs
are widely used Python to read and write files in the computer language, if you want to understand the application procedure, the following article will give you detailed description of relevant content, will help you in the process of learning in the future, here we introduce their applications in detail.

A commonly used method shutil os module and file module in python, folder operations are often used.

1. get the current working directory that the current directory path Python script work: os.getcwd ()
2. Return all files and directories in the specified directory: os.listdir ()
3. function is used to delete a file: os. remove ()
4. remove the plurality of directories: os.removedirs (R & lt "C: \ Python")
5. the given path if a file is: the os.path.isfile ()
6. the given path whether a directory: os.path.isdir ()
7. the determines whether the absolute path: os.path.isabs ()
8. the given path whether really exist: os.path.exists ()
9. the return path of a directory name and file name: The os.path.split ()
example:
code is as follows:
The os.path.split ( '/ Home / Swaroop / byte / code / poem.txt') results: ( '/ home / swaroop / byte / code ',' poem.txt ')

10. The isolated Extension: os.path.splitext ()
11. The path name Get: os.path.dirname ()
12. The Get File Name: os.path.basename ()
13. Run shell command: os.system ()
14. a read and set environment variables: os.getenv () and os.putenv ()
15. a platform gives the current line terminator used: os.linesep Windows using '\ r \ n', Linux using '\ n' the Mac using '\ r'
16. the indication platform you are using: os.name for Windows, it is 'nt', and for Linux / Unix users, it is 'the POSIX'
17. the rename: os.rename (old , new new)
18. The create multi-level directory: os.makdirs (r "c: \ Python \ the Test")
19. The creation of a single directory: os.mkdir ( "the Test")
20. The access to file attributes: os.stat (file)
21. modify file permissions and timestamps: os.chmod (file)
22. the termination of the current process: os.exit ()
23. the get file size: os.path.getsize (filename)

Second, the file operation Daquan

1.os.mknod ( "test.txt") to create an empty file
2.fp = open ( "test.txt", w) directly open a file, if the file does not exist, create a file
3. On the open mode:

r:以读方式打开文件,可读取文件信息。
w:以写方式打开文件,可向文件写入信息。如文件存在,则清空该文件,再写入新内容
a:以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建
b:以二进制模式打开文件,而不是以文本模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。
r+:以读写模式打开
w+:以读写模式打开 (参见 w )
a+:以读写模式打开 (参见 a )
rb:以二进制读模式打开
wb:以二进制写模式打开 (参见 w )
ab:以二进制追加模式打开 (参见 a )
rb+:以二进制读写模式打开 (参见 r+ )
wb+:以二进制读写模式打开 (参见 w+ )
ab+:以二进制读写模式打开 (参见 a+ )

File object methods
f.close (): close the file, remember to use open () after opening the file must remember to turn it off, otherwise it will take up system can open file handles.
f.fileno (): obtain a file descriptor is a digital
f.flush (): flush the output buffer
f.isatty (): If the file is an interactive terminal, it returns True, otherwise False.
f.read ([count]): read the file, if count, then reads out the count bytes.
f.readline (): read a line of information.
f.readlines ():
read all the lines, that is, the entire file is read out information.
f.seek (offset [, where]) : the file pointer to the offset position with respect to where. where 0 is a start of the file, which is the default; 1 indicates a current position; 2 represents the end of the file.
f.tell (): obtain a file pointer position.
f.truncate ([size]): intercepting a file, so that the file size is size.
f.write (string): the string string to the file.
f.writelines (list): a character string in the list written to the file line by line, is continuously written to the file, no line breaks.

fp.read ([size]) #size length read in byte units
fp.readline ([size]) # line is read, if the defined size, it is possible to return only part of a line
fp.readlines ([ size]) # each line of the file as a member of a list and returns the list. In fact, its interior is invoked through the loop readline () to achieve. If the offer size parameters, size is read the contents of the total length, that is possible to read only part of the file.
fp.write (str) # The str written to a file, write () does not add a newline after str
fp.writelines (seq) seq # contents of all written to a file (multi-line one-time write into). This function is only faithfully written not add anything after each line.
fp.close () # close the file. python will turn off automatically after a file without file, but this feature is not guaranteed, it is best to develop their own habits closed. If a file can also be manipulated to produce ValueError after closing
fp.flush () # the contents of the buffer is written to disk
fp.fileno () # returns a long integer "file tag"
fp.isatty () # if the file is a terminal device file (unix system)
fp.tell () # returns the current position mark of the file operation to the beginning of the file as an origin
fp.next () # returns the next line, and the operation flag is shifted to a file the next line. Put a file when used for ... in this sentence file, it is to call the next () function to implement traversal.
fp.seek (offset [, whence]) # playing the file offset of the marker to the operation. This offset is usually relative to the beginning of the file to calculate the generally positive. But whence If a parameter might not, whence the calculation can be expressed from the beginning, 1 indicates the current position as the origin is calculated as 0. 2 represents the end of the file to be calculated as the origin. Note that if a file is opened in a + or mode, every time the write operation, the file operation flag will automatically return to the end of the file.
fp.truncate ([size]) # the documents into a predetermined size, is cut to a default location of the current file operation mark. If the size of the file is larger than the size, according to the system without changing the file may be different, it may be up to the appropriate size with 0 files, it might be a bunch of random stuff to add.

Third, the directory operations Daquan

1. Create a directory

os.mkdir ( "File")
2. Copy the file:
shutil.copyfile ( "oldfile", "newfile") #oldfile and can only be newfile file
shutil.copy ( "oldfile", "newfile ") #oldfile only is the folder, newfile can be a file, it can be the destination directory
3. copy the folder:
4.shutil.copytree ( "olddir", "newdir") #olddir and newdir can only be a directory, and must not exist newdir
5 rename the file (directory)
os.rename ( "oldname", "newname") # files or directories are using this command
6. move the file (directory)
shutil.move ( "OldPos", "NewPOS")
7. delete files
os.remove ( "file")
8. delete the directory
os.rmdir ( "dir") # only delete empty directories
shutil.rmtree ( "dir") # empty directory, the content of the directory can be deleted
9. conversion Catalog
os.chdir ( "path") # change path

Directory operations:
os.mkdir ( "File") Create a directory
to copy files:
shutil.copyfile ( "oldfile", "newfile") can only be oldfile and newfile file
shutil.copy ( "oldfile", "newfile ") oldfile only can be a folder, newfile can be a file, it can also be a target directory
to copy a folder:
shutil.copytree ( "olddir", "newdir") olddir and newdir can only be a directory, and there is no newdir must
rename the file (directory )
os.rename ( "oldname", "newname") is a file or directory use this command to
move a file (directory)
shutil.move ( "OldPos", "NewPOS")
to delete the file
os.remove ( "file")
delete Catalog
os.rmdir ( "dir") can only delete empty directories
shutil.rmtree ( "dir") an empty directory with the contents of the directory can be deleted
conversion directory
os.chdir ( "path") to change path

Example:

 -*- coding: utf-8 -*- 
  
import os 
import shutil 
  
# 一. 路径操作:判断、获取和删除 
  
#1. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 
#print: currentpath: f:\LearnPython 
currentpath = os.getcwd() 
print "currentpath: ",currentpath 
#2. 返回指定目录下的所有文件和目录名:os.listdir() 
#print:os.listdir(): ['test.txt', 'testRW.py', 'test1.txt', 'cmd.py', 'rwfile.py', 'downloadfile.py', 'date.py', 'time.py', 'datetime.py', 'file.py'] 
print "os.listdir(): ",os.listdir('f:\LearnPython') 
  
path = "F:\mmmmmmmmm\debug_taobao_200003@taobao_android1.6_3.2.1.apk"
#3. 判断给出的路径是否真地存:os.path.exists() 
if os.path.exists(path): 
  #删除一个文件:os.remove() 
  os.remove(path) 
else: 
  print path,"not exist"
  
#4. 删除多个目录:os.removedirs(“c:\python”) 
#它只能删除空目录,如果目录里面有内容将不会被删除 
if os.path.exists("d:/woqu"): 
  os.removedirs("d:/woqu") 
else: 
  os.mkdir("d:/woqu") 
  os.removedirs("d:/woqu") 
  
#5. 判断给出的路径是否是一个文件:os.path.isfile() 
#print: True 
print os.path.isfile("D:\hello\json.txt") 
#6. 判断给出的路径是否是一个目录:os.path.isdir() 
#print: True 
print os.path.isdir("D:\hello") 
#7. 判断是否是绝对路径:os.path.isabs() 
#print: True 
print os.path.isabs("D:\hello") 
# 判断是否是链接 
print os.path.islink('http://www.baidu.com') 
#8. 返回一个路径的目录名和文件名:os.path.split()    
#eg os.path.split('/home/swaroop/byte/code/poem.txt') 结果:('/home/swaroop/byte/code', 'poem.txt')  
#print: ('D:\\hello', 'json.txt') 
print os.path.split("D:\hello\json.txt") 
#9. 分离扩展名:os.path.splitext() 
#print:('D:\\hello\\json', '.txt') 
print os.path.splitext("D:\hello\json.txt") 
#10. 获取路径名:os.path.dirname() 
#print: 'D:\\hello' 
print os.path.dirname("D:\hello\json.txt") 
#11. 获取文件名:os.path.basename() 
#print: 'json.txt' 
print os.path.basename("D:\hello\json.txt") 
  
  
#13. 指示你正在使用的平台:os.name    对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix' 
print "os.name: ",os.name 
  
#14. linex 下的命令 
if os.name == 'posix': 
  #读取和设置环境变量:os.getenv() 与os.putenv() 
  home_path = os.environ['HOME'] 
  home_path = os.getenv('HOME') #读取环境变量  
elif os.name == 'nt': 
  home_path = 'd:' 
  print 'home_path: ',home_path 
  
#15. 给出当前平台使用的行终止符:os.linesep  Windows使用'\r\n',Linux使用'\n'而Mac使用'\r' 
print(os.linesep) 
  
#16. 应为windows和linux的路径有点点不一样,windows是用 \\ 来分割的,linux是用 / 来分隔, 
#而用os.sep 会自动根据系统选择用哪个分隔符。 
print(os.sep) 
  
#17. 重命名:os.rename(old, new) 
#先进入目录 
os.chdir("d:\\hello") 
print os.getcwd()  
#18. 再重命名 
os.rename("1.txt", "11.txt") 
#19. 创建多级目录:os.makedirs(“c:\python\test”) 
os.makedirs('d:\h\e\l\l\o') 
#20. 创建单个目录:os.mkdir(“test”) 
os.mkdir('d:\f') 
#21. 获取文件属性:os.stat(file) 
#print: nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=497L, st_atime=1346688000L, st_mtime=1346748054L, st_ctime=1346748052L) 
print os.stat('d:\hello\json.txt') 
#22. 修改文件权限与时间戳:os.chmod(path,mode) 
#这里有介绍:http://blog.csdn.net/wirelessqa/article/details/7974477 
#23. 终止当前进程:os.exit() 
#24. 获取文件大小:os.path.getsize(filename) 
print os.path.getsize('d:/hello/json.txt')

python how to write a list of file:
Example:

a = [1,2,3,4,5,6,7,8,9] 
tmp = [] 
for i in range(0,len(a),3): 
 tmp.append(str(a[i])+","+str(a[i+1])+","+str(a[i+2])+"\n") 
file("./a.txt",'w').writelines(tmp)

python read txt file to the list
Example:
If the contents of the file txt: AAA, BBB, CCC
ddd, Eee, FFF

I want to read to save the list to display the results [[aaa, bbb, ccc], [ddd, eee, fff]]

txtpath=r"a.txt"
fp=open(txtpath) 
arr=[] 
for lines in fp.readlines(): 
  lines=lines.replace("\n","").split(",") 
  arr.append(lines) 
fp.close()
发布了51 篇原创文章 · 获赞 122 · 访问量 8万+

Guess you like

Origin blog.csdn.net/haoxun03/article/details/104348699
Recommended