Python full stack road series file operations

高洛峰
Release: 2017-02-15 15:02:45
Original
1402 people have browsed it

Python can view and create files, and can add, modify, and delete file contents. The functions used are open in Python 3.5.x and in Python 2.7 .x supports both file and open, but the file function was removed in the 3.5.x series.

Python file opening method

文件句柄 = open('文件路径','打开模式')
Copy after login

Ps: The file handle is equivalent to the variable name, and the file path can be written as an absolute path or a relative path.

Python mode for opening files

Basic mode

Mode Description Notes
r Read-only mode The file must exist
w Write-only mode Create the file if the file does not exist, clear the file content if the file exists
x Write-only mode The file is not readable. If the file does not exist, it will be created. If it exists, an error will be reported.
a Append mode The file cannot be read. If the file exists, add the content at the end of the file

Pattern with +

##r+Read and writew+ WRITE READx+WRITE READa+WRITE READ
Mode Description
Pattern with

b

PatternDescriptionrbBinary read modewbBinary write modexbBinary write-only modeabBinary append mode

Tips: When opened in b mode, the content read is of byte type, and the byte type also needs to be provided when writing

With

+Pattern with b

PatternDescriptionrb+Binary read and write modewb+Binary read and write modexb+Binary write-only modeab+Binary read-write mode
Python file reading method

ModeDescriptionread([size])Read the entire content of the file. If size is set, read size bytes for a long timereadline([size])Read line by line##readlines()The test file name is
The content of each line read is used as an element in the list
hello.tx"

, and the file content is: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">Hello Word! 123 abc 456 abc 789 abc</pre><div class="contentsignin">Copy after login</div></div>

read

code :

# 以只读的方式打开文件hello.txt
f = open("hello.txt","r")
# 读取文件内容赋值给变量c
c = f.read()
# 关闭文件
f.close()
# 输出c的值
print(c)
Copy after login

Output result:

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
Hello Word!
123
abc
456
abc
789
abc
Copy after login

readline

Code:

# 以只读模式打开文件hello.txt
f = open("hello.txt","r")
# 读取第一行
c1 = f.readline()
# 读取第二行
c2 = f.readline()
# 读取第三行
c3 = f.readline()
# 关闭文件
f.close()
# 输出读取文件第一行内容
print(c1)
# 输出读取文件第二行内容
print(c2)
# 输出读取文件第三行内容
print(c3)
Copy after login

Output result:

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
Hello Word!

123

abc
Copy after login

readlines

# 以只读的方式打开文件hello.txt
f = open("hello.txt","r")
# 将文件所有内容赋值给c
c = f.readlines()
# 查看数据类型
print(type(c))
# 关闭文件
f.close()
# 遍历输出文件内容
for n in c:
    print(n)
Copy after login
Result

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
# 输出的数据类型
<class &#39;list&#39;>
Hello Word!

123

abc

456

abc

789

abc
Copy after login

Python file writing method

Methodwrite(str)writelines(sequence or strings)

write

代码:

# 以只读的模式打开文件write.txt,没有则创建,有则覆盖内容
file = open("write.txt","w")
# 在文件内容中写入字符串test write
file.write("test write")
# 关闭文件
file.close()
Copy after login

write.txt文件内容为:

test write
Copy after login

writelines

代码:

# 以只读模式打开一个不存在的文件wr_lines.txt
f = open("wr_lines.txt","w",encoding="utf-8")
# 写入一个列表
f.writelines(["11","22","33"])
# 关闭文件
f.close()
Copy after login

wr_lines.txt文件内容:

112233
Copy after login
Copy after login

Python文件操作所提供的方法

close(self):

关闭已经打开的文件

f.close()
Copy after login

fileno(self):

文件描述符

 f = open("hello.txt","r")
ret = f.fileno()
f.close()
print(ret)
Copy after login

执行结果:

3
Copy after login

flush(self):

刷新缓冲区的内容到硬盘中

f.flush()
Copy after login

isatty(self):

判断文件是否是tty设备,如果是tty设备则返回True,否则返回False

f = open("hello.txt","r")
ret = f.isatty()
f.close()
print(ret)
Copy after login

返回结果:

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
False
Copy after login
Copy after login

readable(self):

是否可读,如果可读返回True,否则返回False

f = open("hello.txt","r")
ret = f.readable()
f.close()
print(ret)
Copy after login

返回结果:

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
True
Copy after login
Copy after login

readline(self, limit=-1):

每次仅读取一行数据

f = open("hello.txt","r")
print(f.readline())
print(f.readline())
f.close()
Copy after login

返回结果:

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
Hello Word!

123
Copy after login

readlines(self, hint=-1):

把每一行内容当作列表中的一个元素

f = open("hello.txt","r")
print(f.readlines())
f.close()
Copy after login

返回结果:

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
['Hello Word!\n', '123\n', 'abc\n', '456\n', 'abc\n', '789\n', 'abc']
Copy after login
  • tell(self):

获取指针位置

f = open("hello.txt","r")
print(f.tell())
f.close()
Copy after login

返回结果:

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
0
Copy after login

seek(self, offset, whence=io.SEEK_SET):

指定文件中指针位置

f = open("hello.txt","r")
print(f.tell())
f.seek(3)
print(f.tell())
f.close()
Copy after login

执行结果

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
0
3
Copy after login

seekable(self):

指针是否可操作

f = open("hello.txt","r")
print(f.seekable())
f.close()
Copy after login

执行结果

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
True
Copy after login
Copy after login

writable(self):

是否可写

f = open("hello.txt","r")
print(f.writable())
f.close()
Copy after login

执行结果

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
False
Copy after login
Copy after login

writelines(self, lines):

写入文件的字符串序列,序列可以是任何迭代的对象字符串生产,通常是一个字符串列表

f = open("wr_lines.txt","w")
f.writelines(["11","22","33"])
f.close()
Copy after login

执行结果

112233
Copy after login
Copy after login

read(self, n=None):

读取指定字节数据,后面不加参数默认读取全部

f = open("wr_lines.txt","r")
print(f.read(3))
f.seek(0)
print(f.read())
f.close()
Copy after login

执行结果

C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py
112
112233
Copy after login

write(self, s):

往文件里面写内容

f = open("wr_lines.txt","w")
f.write("abcabcabc")
f.close()
Copy after login

文件内容

abcabcabc
Copy after login

同时打开多个文件

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:
 代码块
Copy after login

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:
    pass
Copy after login

更多Python全栈之路系列之文件操作相关文章请关注PHP中文网!



Description
Write string to file
Write multiple lines to the file. The parameter can be an iterable object, list, tuple, etc.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template