File Basics

File
a: absolute and relative paths
encoding: utf-8 gbk
operation: read-only, write-only, append, write, write-read and the like.
1.1 absolute path: from the beginning has been the root directory of the disk to the file name d: \ aaa.txt
1.2.2 relative path: a file folder, file relative to the current terms if this program is located in the same file, the relative path name of the file. If we have to use up one folder ../ relative path, you can write directly to the file name.
II: a file operation process
. Open the file # 1, and obtain the file handle assigned to a variable
f = open ( 'a.txt', 'r', encoding = 'utf-8') # default open mode is on r

# 2. By operating the handle of the file
data = f.read ()

#3. 关闭文件
f.close()
列如:
f=open(r'd:\aa.txt',mode='r',encoding='gbk')
content=f.read()
print(content)
f.close()

Two: file operations
1.r read mode
1.1read ()
the Read () to read the contents of files all out; drawbacks if the file will be very large memory footprint, easily lead to memory Ben collapse.
1.2read (the n-)
the Read () specify what position the read time to read
in the mode r, n in accordance with the read characters.
1.3readline ()
the readline () reads a time to read a row Precautions: readline () has a data read out of the back \ n

2.写入模式
f=open(r'd:\aa.txt',mode='w+',encoding='gbk')
content1=f.write('dsag')
print(content1)
f.close()

3. append mode
F = Open (r'd: \ aa.txt ', MODE =' A ', encoding =' GBK ')
content1 = f.write (' dvdg ')
Print (content1)
f.close ()
if file does not exist, the use of a file operation mode, then it will create the file, and then write the content.
If the file exists, use a file operation mode, then it will face additional content in the final document.

 

Guess you like

Origin www.cnblogs.com/lxx99/p/11655886.html