文件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