1,linux文件知识补充
~$
ls
-all
drwxr-xr-x 2 qiaozan qiaozan 4096 8月 6 21:21 Templates
-rw-r--r-- 1 qiaozan qiaozan 0 9月 17 07:53 test.txt
解读:
d和-分别代表目录和普通文件。
rwxr-xr-x分别代表"(用户/用户组/其它用户)“的”(可读/可写/可执行)"权限。
可以使用chmod修改文件权限。
如:linux中给一个文件加可执行权限:**
chmod +x 文件
或用0~7的数字
chmod 777 文件
不行加sudo
2,python文件的打开方式:
open([文件路径]文件名,[读/写/追加/以二进制形式等文件打开mode],[encoding="UTF-8"])
返回一个文件对象
注意:
以二进制形式打开文件进行读写是对所有文件通用的
。
如:open([文件路径]文件名,“rb”)
文件的打开模式mode(注意不同的打开模式有不同的操作权限,如以只读“r”的方式打开就不能有写等其它操作,mode之间可以叠加,写在一起就行,但要注意mode不能出现"wr"等模式,如果要同时读写需要加“+”号,在这种情况下,读写共享一个文件指针,所以要格外注意),注意每次操作完后最好立即关闭,下次再操作再打开就好了:
3,python读取方式:**
test.txt文件内容如下:
第1行 123456789
第2行 123456789
第3行 123456789
第4行 123456789
第5行 123456789
第6行 123456789
第7行 123456789
第8行 123456789
1),read([size]):读取文件,size可选,若没有指定size默认为读取文件的全部,指定size则每次读取size个字节bytes,文件指针后移size个字节,若文件剩余的不足size个字节,则返回剩余的字节,下同 。
f
=
open
(
"test.txt"
,
"rb"
)
res
=
f
.
read
(
)
print
(
res
)
结果:
第
1
行
123456789
第
2
行
123456789
第
3
行
123456789
第
4
行
123456789
第
5
行
123456789
第
6
行
123456789
第
7
行
123456789
第
8
行
123456789
[
Finished
in
0.
2s
]
指定size:
f
=
open
(
"test.txt"
,
"r"
,
encoding
=
"UTF-8"
)
res
=
f
.
read
(
4
)
#第1行
print
(
res
)
若文件剩余的没有size个字节,则返回剩余的字节:
f
=
open
(
"test.txt"
,
"r"
,
encoding
=
"UTF-8"
)
res
=
f
.
read
(
1000
)
print
(
res
)
结果:
第
1
行
123456789
第
2
行
123456789
第
3
行
123456789
第
4
行
123456789
第
5
行
123456789
第
6
行
123456789
第
7
行
123456789
第
8
行
123456789
[
Finished
in
0.
1s
]
2),readline([size]):读取一行,size可选,size是对一行中的读取字节数进行限制,若一行中没有size个字节,则返回完整的一行
f
=
open
(
"test.txt"
,
"r"
,
encoding
=
"UTF-8"
)
res
=
f
.
readline
(
)
print
(
res
)
结果:
第
1
行
123456789
[
Finished
in
0.
1s
]
指定size:
f
=
open
(
"test.txt"
,
"r"
,
encoding
=
"UTF-8"
)
res
=
f
.
readline
(
4
)
#第1行
res
=
f
.
readline
(
400
)
#第1行 123456789
print
(
res
)
3),readlines([size]):读取整个文件,并返回文件所有行组成的列表。size可选
f
=
open
(
"test.txt"
,
"r"
,
encoding
=
"UTF-8"
)
res
=
f
.
readlines
(
)
print
(
res
)
结果返回是列表:
[
'第1行 123456789\n'
,
'第2行 123456789\n'
,
'第3行 123456789\n'
,
'第4行 123456789\n'
,
'第5行 123456789\n'
,
'第6行 123456789\n'
,
'第7行 123456789\n'
,
'第8行 123456789\n'
]
[
Finished
in
0.
1s
]
指定size时,:
f
=
open
(
"test.txt"
,
"r"
,
encoding
=
"UTF-8"
)
# res = f.readlines(3) # ['第1行 123456789\n']
# res = f.readlines(10) # ['第1行 123456789\n']
# res = f.readlines(20) #['第1行 123456789\n', '第2行 123456789\n']
res
=
f
.
readlines
(
30
)
# ['第1行 123456789\n', '第2行 123456789\n', '第3行 123456789\n']
print
(
res
)
4,python文件写入方式:
1)write(str) -> None.:将字符串写入文件
函数原型:
write(…)
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
2)writelines(sequence_of_strings) -> None.写入多行到文件
函数原型:
writelines(...)
writelines(sequence_of_strings) -> None. Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
5,tell() 和seek的用法演示
f
=
open
(
"test.txt"
,
"r+"
,
encoding
=
"UTF-8"
)
# test.txt文件为空文件
res
=
f
.
write
(
"hello!"
)
print
(
f
.
tell
(
)
)
# 6 写之后文件指针处于第六个字节处,也就是文件末尾EOF
res
=
f
.
read
(
)
# 此时读什么也读不到,因文件指针处于文件末尾EOF
print
(
f
.
tell
(
)
)
# 6
f
.
seek
(
0
,
0
)
# seek(偏移量,基准whence),whence取值(0代表文件开头,1代表当前,2代表文件末尾),此处将文件指针重定位到文件开头,偏移量为0的位置
print
(
f
.
tell
(
)
)
# 0 可见已经定位到开头了。
res
=
f
.
read
(
)
# hello!
print
(
res
)
6,文件的读写存在缓存机制
文件的读写存在缓存机制,当缓存满了或者文件刷新(使用 flush强制刷新 /程序正常运行结束/文件被close)都会导致实际的IO操作. 当你在一次打开多次写操作时就要注意考虑及时进行flush了,否则程序的异常终止会导致缓存中的数据丢失!
7,推荐结合with语句打开文件
with
open
(
'filename'
,
method
=
''
)
as
file_object
:
content
=
file_object
.
read
(
)
特点
1. with语句打开文件,并指示了一个语句块(即接下来有一个缩进的多行代码区域),该语句块内的代码是对文件的
操作,当脱离该语句块时(即没有了缩进),则表示with语句块结束,接下来的代码不是对文件的操作代码。
2. 注意,当脱离with语句块的时候,即表示结束了文件的操作,这是python会自动调用 close() 关闭这个文件,
此后不能再引用这个文件对象。
优点
1.使用简单方便。
2.自动管理文件对象,不必使用 close()
3.当遭遇程序bug时导致本来应有的 close() 未能执行,如果使用with,python保证即使出现故障,也能保证文件被
正确关闭
python file对象的所有方法如下:
|
close
(
..
.
)
|
close
(
)
-
>
None or
(
perhaps
)
an integer. Close the file.
|
|
Sets data attribute .closed to True. A closed
file
cannot be used
for
|
further I/O operations. close
(
)
may be called
more
than once without
|
error. Some kinds of
file
objects
(
for example, opened by popen
(
))
|
may
return
an
exit
status upon closing.
|
|
fileno
(
..
.
)
|
fileno
(
)
-
>
integer
"file descriptor"
.
|
|
This is needed
for
lower-level
file
interfaces, such os.read
(
)
.
|
|
flush
(
..
.
)
|
flush
(
)
-
>
None. Flush the internal I/O buffer.
|
|
isatty
(
..
.
)
|
isatty
(
)
-
>
true
or false. True
if
the
file
is connected to a
tty
device.
|
|
next
(
..
.
)
|
x.next
(
)
-
>
the next value, or raise StopIteration
|
|
read
(
..
.
)
|
read
(
[
size
]
)
-
>
read
at
most
size bytes, returned as a string.
|
|
If the size argument is negative or omitted,
read
until
EOF is reached.
|
Notice that when
in
non-blocking mode,
less
data than what was requested
|
may be returned, even
if
no size parameter was given.
|
readinto
(
..
.
)
|
readinto
(
)
-
>
Undocumented. Don't use this
;
it may go away.
|
|
readline
(
..
.
)
|
readline
(
[
size
]
)
-
>
next line from the file, as a string.
|
|
Retain newline. A non-negative size argument limits the maximum
|
number of bytes to
return
(
an incomplete line may be returned then
)
.
|
Return an empty string at EOF.
|
|
readlines
(
..
.
)
|
readlines
(
[
size
]
)
-
>
list of strings, each a line from the file.
|
|
Call readline
(
)
repeatedly and
return
a list of the lines so read.
|
The optional size argument,
if
given, is an approximate bound on the
|
total number of bytes
in
the lines returned.
|
|
seek
(
..
.
)
|
seek
(
offset
[
, whence
]
)
-
>
None. Move to new
file
position.
|
|
Argument offset is a byte count. Optional argument whence defaults to
|
0
(
offset from start of file, offset should be
>=
0
)
;
other values are 1
|
(
move relative to current position, positive or negative
)
, and 2
(
move
|
relative to end of file, usually negative, although many platforms allow
|
seeking beyond the end of a file
)
. If the
file
is opened
in
text mode,
|
only offsets returned by tell
(
)
are legal. Use of other offsets causes
|
undefined behavior.
|
Note that not all
file
objects are seekable.
|
tell
(
..
.
)
|
tell
(
)
-
>
current
file
position, an integer
(
may be a long integer
)
.
|
|
truncate
(
..
.
)
|
truncate
(
[
size
]
)
-
>
None. Truncate the
file
to at
most
size bytes.
|
|
Size defaults to the current
file
position, as returned by tell
(
)
.
|
|
write
(
..
.
)
|
write
(
str
)
-
>
None. Write string str to file.
|
|
Note that due to buffering, flush
(
)
or close
(
)
may be needed before
|
the
file
on disk reflects the data written.
|
|
writelines
(
..
.
)
|
writelines
(
sequence_of_strings
)
-
>
None. Write the strings to the file.
|
|
Note that newlines are not added. The sequence can be any iterable object
|
producing strings. This is equivalent to calling write
(
)
for
each string.
|
|
xreadlines
(
..
.
)
|
xreadlines
(
)
-
>
returns self.
|
|
For backward compatibility. File objects now include the performance
|
optimizations previously implemented
in
the xreadlines module.