1. 程式人生 > >python 讀寫文件

python 讀寫文件

包括 stat method fse reference -c 填充 pos body


# python 讀寫文件


## 代碼
-----------------------------
``` python
#! /usr/bin/python
import os,sys

try:
fsock = open("D:/SVNtest/test.py", "r")
except IOError:
print "The file don‘t exist, Please double check!"
exit()
print ‘The file mode is ‘,fsock.mode
print ‘The file name is ‘,fsock.name
P = fsock.tell()

print ‘the postion is %d‘ %(P)
fsock.close()

#Read file
fsock = open("D:/SVNtest/test.py", "r")
AllLines = fsock.readlines()
#Method 1
for EachLine in fsock:
print EachLine

#Method 2
print ‘Star‘+‘=‘*30
for EachLine in AllLines:
print EachLine
print ‘End‘+‘=‘*30
fsock.close()

#write this file
fsock = open("D:/SVNtest/test.py", "a")

fsock.write("""
#Line 1 Just for test purpose
#Line 2 Just for test purpose
#Line 3 Just for test purpose""")
fsock.close()


#check the file status
S1 = fsock.closed
if True == S1:
print ‘the file is closed‘
else:
print ‘The file donot close‘
```

## 引用
-----------------------------
- [菜鳥教程](http://www.runoob.com/python/file-methods.html)

Python File(文件) 方法

file 對象使用 open 函數來創建,下表列出了 file 對象常用的函數:

序號方法及描述
1

file.close()

關閉文件。關閉後文件不能再進行讀寫操作。

2

file.flush()

刷新文件內部緩沖,直接把內部緩沖區的數據立刻寫入文件, 而不是被動的等待輸出緩沖區寫入。

3

file.fileno()

返回一個整型的文件描述符(file descriptor FD 整型), 可以用在如os模塊的read方法等一些底層操作上。

4

file.isatty()

如果文件連接到一個終端設備返回 True,否則返回 False。

5

file.next()

返回文件下一行。

6

file.read([size])

從文件讀取指定的字節數,如果未給定或為負則讀取所有。

7

file.readline([size])

讀取整行,包括 "\n" 字符。

8

file.readlines([sizehint])

讀取所有行並返回列表,若給定sizeint>0,返回總和大約為sizeint字節的行, 實際讀取值可能比sizhint較大, 因為需要填充緩沖區。

9

file.seek(offset[, whence])

設置文件當前位置

10

file.tell()

返回文件當前位置。

11

file.truncate([size])

截取文件,截取的字節通過size指定,默認為當前文件位置。

12

file.write(str)

將字符串寫入文件,沒有返回值。

13

file.writelines(sequence)

向文件寫入一個序列字符串列表,如果需要換行則要自己加入每行的換行符。

python 讀寫文件