python类库31[读写文件]

本文介绍了Python中使用open函数进行文件操作的方法,包括不同模式下的读写操作,并通过具体实例展示了如何打开、读取和写入文件,以及如何利用linecache模块获取特定行的内容。


一 Open 函数

open(path [,mode [,buffersize]])

1)path文件的路径。

2)mode文件的读写模式。

r读打开存在的文件,

w写打开文件,如果文件存在以前的内容被覆盖,如果文件不存在则创建之,

a打开存在的文件添加新内容,

r+读写打开文件,以前的被人被保留,

w+读写打开文件,以前的内容被覆盖,

a+读写打开文件,以前的被人被保留,

b与rwa之一配合使用,表示以二进制打开,

u与rwa之一配合使用,Applies the "universal" newline translator to the file as it is opened.

3)buffersize指定访问文件时的buffer模式。

0表示不使用buffer,

1表示行buffer,

其他的正整数表示buffer的大小,

当忽略或为负数时使用默认的buffersize。


二 实例

 

outPath = "text.txt"
inPath 
= outPath
print('---------------------------------')
#Open a file for writing
file = open(outPath, 'w')
if file:
    file.write(
'hello\ntom\n')
    file.writelines(
'bye!')
    file.close()
else:
    
print ("Error Opening File.")
    
print('---------------------------------')
#Open a file for reading
file = open(inPath, 'r')
if file:
    
print(file.read())
    
#print(file.readlines())
    file.close()
else:
    
print ("Error Opening File.")

print('---------------------------------')
# read line from file
import linecache
filePath 
= "text.txt"

print (linecache.getline(filePath, 1))
print (linecache.getline(filePath, 3))
linecache.clearcache()

print('---------------------------------')
# read word from file
filePath = "input.txt"
wordList 
= []
wordCount 
= 0

#Read lines into a list
file = open(filePath, 'rU')
for line in file:
    
for word in line.split():
        wordList.append(word)
        wordCount 
+= 1
print (wordList)
print ("Total words = %d" % wordCount)

print('---------------------------------')
# count line of file
filePath = "input.txt"
lineCount 
= len(open(filePath, 'rU').readlines())
print ("File %s has %d lines." % (filePath,lineCount))


完!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值