python实现文件读写的一段代码

发布时间:2020-10-05编辑:脚本学堂
本文介绍下,用python实现文件读写的代码实例,有需要的朋友,可以作为学习资料参考下。

1,python读取文件内容
 

复制代码 代码示例:

#!/usr/bin/python
# Filename: readfile.py

header = '''
abc
def
ghi
jkl
mno
'''

f = file('header.txt', 'w') # open for 'w'riting
f.write(header) # write text to file
f.close() # close the file

f = file('header.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
    line = f.readline()
    if len(line) == 0: # Zero length indicates EOF
        break
    print line,
    # Notice comma to avoid automatic newline added by Python
f.close() # close the file

2,用Python创建一个新文件,内容是从0到9的整数, 每个数字占一行:
 

复制代码 代码示例:
>>>f=open('f.txt','w')    # r只读,w可写,a追加
>>>for i in range(0,10):f.write(str(i)+'n')
.  .  .
>>> f.close()

3,文件内容追加,从0到9的10个随机整数:
 

复制代码 代码示例:
>>>import random
>>>f=open('f.txt','a')
>>>for i in range(0,10):f.write(str(random.randint(0,9)))
.  .  .
>>>f.write('n')
>>>f.close()

4,文件内容追加,从0到9的随机整数, 10个数字一行,共10行:
 

复制代码 代码示例:
>>> import random
>>> f=open('f.txt','a')
>>> for i in range(0,10):
.  .  .     for i in range(0,10):f.write(str(random.randint(0,9))) 
.  .  .     f.write('n')    
.  .  .
>>> f.close()

5,把标准输出定向到文件:
 

复制代码 代码示例:
>>> import sys
>>> sys.stdout = open("stdout.txt", "w")
>>>  . . .