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分別代表"(用戶/用戶組/其它用戶)“的”(可讀/可寫/可執(zhí)行)"權(quán)限。
可以使用chmod修改文件權(quán)限。
如:linux中給一個文件加可執(zhí)行權(quán)限:**
chmod +x 文件
或用0~7的數(shù)字
chmod 777 文件
不行加sudo
2,python文件的打開方式:
open([文件路徑]文件名,[讀/寫/追加/以二進制形式等文件打開mode],[encoding="UTF-8"])
返回一個文件對象
注意:
以二進制形式打開文件進行讀寫是對所有文件通用的
。
如:open([文件路徑]文件名,“rb”)
文件的打開模式mode(注意不同的打開模式有不同的操作權(quán)限,如以只讀“r”的方式打開就不能有寫等其它操作,mode之間可以疊加,寫在一起就行,但要注意mode不能出現(xiàn)"wr"等模式,如果要同時讀寫需要加“+”號,在這種情況下,讀寫共享一個文件指針,所以要格外注意),注意每次操作完后最好立即關(guān)閉,下次再操作再打開就好了:
3,python讀取方式:**
test.txt文件內(nèi)容如下:
第1行 123456789
第2行 123456789
第3行 123456789
第4行 123456789
第5行 123456789
第6行 123456789
第7行 123456789
第8行 123456789
1),read([size]):讀取文件,size可選,若沒有指定size默認為讀取文件的全部,指定size則每次讀取size個字節(jié)bytes,文件指針后移size個字節(jié),若文件剩余的不足size個字節(jié),則返回剩余的字節(jié),下同 。
f
=
open
(
"test.txt"
,
"rb"
)
res
=
f
.
read
(
)
print
(
res
)
結(jié)果:
第
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個字節(jié),則返回剩余的字節(jié):
f
=
open
(
"test.txt"
,
"r"
,
encoding
=
"UTF-8"
)
res
=
f
.
read
(
1000
)
print
(
res
)
結(jié)果:
第
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是對一行中的讀取字節(jié)數(shù)進行限制,若一行中沒有size個字節(jié),則返回完整的一行
f
=
open
(
"test.txt"
,
"r"
,
encoding
=
"UTF-8"
)
res
=
f
.
readline
(
)
print
(
res
)
結(jié)果:
第
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
)
結(jié)果返回是列表:
[
'第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.:將字符串寫入文件
函數(shù)原型:
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.寫入多行到文件
函數(shù)原型:
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 寫之后文件指針處于第六個字節(jié)處,也就是文件末尾EOF
res
=
f
.
read
(
)
# 此時讀什么也讀不到,因文件指針處于文件末尾EOF
print
(
f
.
tell
(
)
)
# 6
f
.
seek
(
0
,
0
)
# seek(偏移量,基準(zhǔn)whence),whence取值(0代表文件開頭,1代表當(dāng)前,2代表文件末尾),此處將文件指針重定位到文件開頭,偏移量為0的位置
print
(
f
.
tell
(
)
)
# 0 可見已經(jīng)定位到開頭了。
res
=
f
.
read
(
)
# hello!
print
(
res
)
6,文件的讀寫存在緩存機制
文件的讀寫存在緩存機制,當(dāng)緩存滿了或者文件刷新(使用 flush強制刷新 /程序正常運行結(jié)束/文件被close)都會導(dǎo)致實際的IO操作. 當(dāng)你在一次打開多次寫操作時就要注意考慮及時進行flush了,否則程序的異常終止會導(dǎo)致緩存中的數(shù)據(jù)丟失!
7,推薦結(jié)合with語句打開文件
with
open
(
'filename'
,
method
=
''
)
as
file_object
:
content
=
file_object
.
read
(
)
特點
1. with語句打開文件,并指示了一個語句塊(即接下來有一個縮進的多行代碼區(qū)域),該語句塊內(nèi)的代碼是對文件的
操作,當(dāng)脫離該語句塊時(即沒有了縮進),則表示with語句塊結(jié)束,接下來的代碼不是對文件的操作代碼。
2. 注意,當(dāng)脫離with語句塊的時候,即表示結(jié)束了文件的操作,這是python會自動調(diào)用 close() 關(guān)閉這個文件,
此后不能再引用這個文件對象。
優(yōu)點
1.使用簡單方便。
2.自動管理文件對象,不必使用 close()
3.當(dāng)遭遇程序bug時導(dǎo)致本來應(yīng)有的 close() 未能執(zhí)行,如果使用with,python保證即使出現(xiàn)故障,也能保證文件被
正確關(guān)閉
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.
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
