Python notes (file read/write)

Source: Internet
Author: User
Tags create directory mkdir parent directory readline


File reading and writing is a more important part, which is more common in practical application. The program reads the file mainly in three steps, open-read-close.
Open the file using the Open function, read using the Read function, and turn off the use of the close function.

Suppose the C disk has a 1.txt file, the text content is 12345, reads inside the content uses the code:

F=open (' C:\\1.txt ', ' R ')
Print (F.read ())
F.close

Returns 12345. In the Open function, note the symbol escape.

Write to File:

Using the Write function, suppose that you need to continue writing to 678910 in the document, and the code is:

F=open (' C:\\1.txt ', ' W ')
F.write (' 678910 ')
F.close

Notice here is the second parameter of open, the parameter is w for write, R is read, use the Write function will overwrite the previous content, that is, before the write operation to empty the original content.
If you need to continue, open opens with a, and the code is:

F=open (' C:\\1.txt ', ' a ')
F.write (' 678910 ')
F.close
G=open (' C:\\1.txt ', ' R ')
Print (G.read ())
G.close

Return 12345678910

As you can see, this is really very simple under the object-oriented mechanism of Python. It is important to note that when you use the "W" method to write the data in the file again, all the original content will be deleted. If you want to keep the original content, you can use the "a" method to end the file with additional data:

1. FileHandle = open (' Test.txt ', ' a ')
2. Filehandle.write (' \n\nbottom line. ')
3. Filehandle.close ()

FileHandle = open (' Test.txt ', ' a ')
Filehandle.write (' \n\nbottom line. ')
Filehandle.close ()

We then read the Test.txt and display the contents:

1. FileHandle = open (' Test.txt ')
2. Print Filehandle.read ()
3. Filehandle.close ()

FileHandle = open (' Test.txt ')
Print Filehandle.read ()
Filehandle.close ()

The above statement reads the entire file and displays the data in it. We can also read a line in the file:

1. FileHandle = open (' Test.txt ')
2. Print filehandle.readline () # "This is a test."
3. Filehandle.close ()

FileHandle = open (' Test.txt ')
Print filehandle.readline () # "This is a test."
Filehandle.close ()


You can also save the contents of a file to a list:

1. FileHandle = open (' Test.txt ')
2. FileList = Filehandle.readlines () <div></div>
3. For fileline in FileList:
4. print ' >> ', fileline
5. Filehandle.close ()

FileHandle = open (' Test.txt ')
FileList = Filehandle.readlines ()
For Fileline in FileList:
print ' >> ', fileline
Filehandle.close ()

When Python reads a file, it remembers its location in the file, as follows:

1. FileHandle = open (' Test.txt ')
2. Garbage = Filehandle.readline ()
3. Filehandle.readline () # "Really, it is." Filehandle.close ()

FileHandle = open (' Test.txt ')
garbage = Filehandle.readline ()
Filehandle.readline () # "Really, it is." Filehandle.close ()

As you can see, only the second line shows up. However, we can get Python to read from the beginning to solve this problem:

1. FileHandle = open (' Test.txt ')
2. Garbage = Filehandle.readline ()
3. Filehandle.seek (0)
4. Print filehandle.readline () # "This is a test."
5. Filehandle.close ()

FileHandle = open (' Test.txt ')
garbage = Filehandle.readline ()
Filehandle.seek (0)
Print filehandle.readline () # "This is a test."
Filehandle.close ()

In the example above, we let Python read the data from the first byte of the file. So the first line of text is displayed. Of course, we can also get Python's location in the file:

1. FileHandle = open (' Test.txt ')
2. Print filehandle.readline () # "This is a test."
3. Print Filehandle.tell () # "17"
4. Print filehandle.readline () # "Really, it is."

FileHandle = open (' Test.txt ')
Print filehandle.readline () # "This is a test."
Print Filehandle.tell () # "17"
Print filehandle.readline () # "Really, it is."

Or read a few bytes of content at a time in a file:

1. FileHandle = open (' Test.txt ')
2. Print Filehandle.read (1) # "T"
3. Filehandle.seek (4)
4. Print Filehandle.read (1) # "" (Original error)

FileHandle = open (' Test.txt ')
Print Filehandle.read (1) # "T"
Filehandle.seek (4)
Print Filehandle.read (1) # "" (Original error)

In Windows and Macintosh environments, you may sometimes need to read and write files in binary form, such as pictures and executables. At this point, just add a "B" to the way the file is opened:

1. FileHandle = open (' TestBinary.txt ', ' WB ')
2. Filehandle.write (' There is no spoon. ')
3. Filehandle.close ()

FileHandle = open (' TestBinary.txt ', ' WB ')
Filehandle.write (' There is no spoon. ')
Filehandle.close ()

1. FileHandle = open (' TestBinary.txt ', ' RB ')
2. Print Filehandle.read ()
3. Filehandle.close ()

FileHandle = open (' TestBinary.txt ', ' RB ')
Print Filehandle.read ()
Filehandle.close ()


Example

Records commonly used file writes, reads, files, directory operations.

Import time
Import Random

#打开模式列表:
#w opened in writing,
#a Open in Append mode (start with EOF, create new file if necessary)
#r + Open in read-write mode
#w + Open in read/write mode (see W)
#a + Open in read and write mode (see a)
#rb Open in binary read mode
#wb opens in binary write mode (see W)
#ab opens in binary append mode (see a)
#rb + open in binary read and write mode (see r+)
#wb + open in binary read and write mode (see w+)
#ab + open in binary read and write mode (see A +)
f = open (' Tpm.txt ', ' + ')

For I in range (10):
F.write (Time.strftime ('%y-%m-%d%h:%m:%s '))
F.write (' + str (random.randint (0, I)) + ' \ n ')

F.close ()

2. File read

f = open (' Tpm.txt ')
# Read Way Reads
s = F.read ()
Print (S, ' \n\n\n ')
Print (F.tell ())
#上面读取完后指针移动到最后, move the file pointer to the file header by seek
F.seek (0)
#使用readline每次读取一行
while (True):
line = F.readline ()
Print (line)
if (len (line) = = 0):
Break

F.close ()

3. File directory operation (OS package)


#os模块, a series of functions that process files and directories
Import OS

#打印当前目录下的所有文件 Non-recursion
Print (Os.listdir (OS.GETCWD ()))

#切换目录为当前目录
Os.chdir ('. ')

#判断目标是否存在, create if not present
if (os.path.exists ('./osdirs ') = = False):
Os.mkdir ("./osdirs")

#重命名文件或目录名
if (Os.path.exists ("./os") = = False):
Os.rename ("./osdirs", "./os")

#rmdir删除目录, you need to empty the subdirectory or folder in the file first
#removedirs可多层删除目录 (requires no files in the directory) Makedirs can create multiple tiers of directories
if (Os.path.isdir ("./os")):
Os.rmdir ("./os")

#删除文件
if (os.path.exists ('./tpm.txt ')):
Os.remove ('./tpm.txt ')

Common methods and properties in OS modules:


Property
String of split lines in Os.linesep file
Separator for os.sep file path name
Os.curdir the string name of the current working directory
Os.pardir Parent Directory String name
Method
Os.remove () Delete file
Os.rename () Renaming files
Os.walk () Generate all file names under the directory tree
Os.chdir () Change Directory
Os.mkdir/makedirs Create directory/multi-tier directory
Os.rmdir/removedirs Delete directory/multi-tier directory
Listdir () lists the files for the specified directory
GETCWD () Get the current working directory (work directory)
chmod () Change directory permissions
Os.path.basename () Remove directory path, return filename
Os.path.dirname () Remove filename, return directory path
Os.path.join () combines the separated parts into a path name
Os.path.split () returns (DirName (), basename ()) tuple
Os.path.splitext () (return filename,extension) tuple
Os.path.getatime\ctime\mtime returns the most recent access, creation, modification time, respectively
Os.path.getsize () returns the file size
Whether the os.path.exists () exists
Whether the Os.path.isabs () is an absolute path
Os.path.isdir () is a directory
Os.path.isfile () is a file

4. File directory operation (Shutil package)


Import OS
Import Shutil

#复制文件, equivalent to CP command
Shutil.copy (' Start2.txt ', ' Start3 ')

#移动文件或目录, equivalent to MV command.
Shutil.move (' Start3 ', ' start4 ')

if (os.path.exists ('./a/b/c ') = = False):
Os.makedirs ('./a/b/c ')
#删除目录
Shutil.rmtree ('. a ')

if (os.path.exists ('./a/b/c/d ') = = False):
Os.makedirs ('./a/b/c/d ')

#复制目录
if (os.path.exists (' b ') = = False):
Shutil.copytree (' A ', ' B ')

Common methods in Shutil

CopyFile (SRC, DST) is copied from source Src to DST. Of course, the premise is that the destination address is writable. The exception information thrown is IOException. If the current DST already exists, it will be overwritten.
Copymode (SRC, DST) just copy their permissions other things are not going to be copied
Copystat (SRC, DST) replication permissions, last access time, last modified time
Copy (SRC, DST) copies a file to a file or a directory
Copy2 (SRC, DST) copy files on copy the last access time and the modification time also copied over, something similar to cp–p.
Copy2 (SRC, DST) if the two-position file system is the same as the rename operation, just renamed; if it's not in the same file system, move is done.
Copytree (olddir,newdir,true/flase) copies a copy of the Olddir Newdir, if the 3rd argument is True, the symbol connection under the folder is maintained when the directory is replicated, if the 3rd argument is false, The physical copy will be generated in the copied directory instead of the symbolic connection
Rmtree (path[, ignore_errors[, onerror]) Delete directory
Move (SRC, DST) moving files or directories

5, Application-Traverse Folder

Import OS
#遍历当前路劲下的所有目录和文件夹
#返回元组包含三个参数: 1. Parent Directory 2. All folder names (without paths) 3. All file names
For Root, dirs, the files in Os.walk (OS.GETCWD ()):
#输出文件夹信息
For dir in dirs:
Print (Os.path.join (root,dir))
#输出文件信息
For file in Files:
Print (Os.path.join (root,file))

6, summary
Python file operations like PHP, there are ready-made functions to implement, so basically remember the commonly used functions can be

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.