文件操作

 

文件01

#read方法--读取文件
#open函数的第一个参数


# 1.打开文件
file = open('wenjian01')

# 2.操作文件 读/
# read方法:读取文件内容(一次性返回文件的所有内容)
test = file.read()
print test

# 3.关闭文件
# close方法:负责关闭文件
file.close()

在开发中,通常会先编写打开和关闭的代码

 

 

 

文件02

 

 

#read方法--读取文件
#open函数的第一个参数


# 1.打开文件
file = open('wenjian01')

# 2.操作文件 读/
# read方法:读取文件内容(一次性返回文件的所有内容)
text = file.read()
print text

print '*' 50

第一次读取的时候,文件指针移动到文件的末尾
再次调用不会读取任何内容
text = file.read()
print text


# 3.关闭文件
# close方法:负责关闭文件
file.close()

 

 

 

文件03

# 1.打开文件
file = open('wenjian01')

# 2.操作文件 读/
# read方法:读取文件内容(一次性返回文件的所有内容)
text = file.read()
print text


打印输入内容的长度
print type(text)
print len(text)

print '*' 50
text = file.read()
print text
print len(text)



# 3.关闭文件
# close方法:负责关闭文件
file.close()

 

文件04

#以写的方式打开文件,如果文件存在会被覆盖.如果文件不存在,

#1.打开文件
file = open('REDME','a')

#2.写入文件
file.write('linux')

 

 

 

#以追方式打开文件
#如果该


读取大文件的正确姿势
file = open('wenjian01')

为什么要写成死循环:因为我们不知道要读取的文件有多少行
while True:
    text = file.readline()
    如果文件指针到最后以行,那么就读不到内容了
    if not text:
        break
        #每读取一个行,末尾都已经有一个\n
    print text
file.close()

 

 

 

 

 

文件05

 

# 1.打开文件
#源文件以只读的方式打开
file_read = open('wenjian01')
#目标文件以前的方式打开
file_write = open('wenjian_copy','w')

#从源文件中读取内容
text = file_read.read()
#将读取到的内容写到目标文件中
file_write.write(text)

#关闭文件
file_read.close()

file_write.close()

 

 

 

 

# 1.打开文件
#源文件以只读的方式打开
file_read = open('wenjian01')
#目标文件以前的方式打开
file_write = open('wenjian_copy2','w')


#读写
while True:
    text = file_read.readline()
    if not text:
        break
    file_write.write(text)


#关闭文件
file_read.close()

file_write.close()

 

 

 

wenjian01

linux
linux
linux
linux
linux
linux

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值