5.1丶文件的读写

文件的读写

<1>写数据(write)

使用write()可以完成向文件写入数据

demo:

f = open('test.txt', 'w')
f.write('hello world, i am here!')
f.close()

运行现象:

注意:

  • 如果文件不存在那么创建,如果存在那么就先清空,然后写入数据

<2>读数据(read)

使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据

demo:

f = open('test.txt', 'r')

content = f.read(5)

print(content)

print("-"*30)

content = f.read()

print(content)

f.close()

运行现象:

注意:

  • 如果open是打开一个文件,那么可以不用谢打开的模式,即只写 open('test.txt')
  • 如果使用读了多次,那么后面读取的数据是从上次读完后的位置开始的

<3>读数据(readlines)

就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素

#coding=utf-8

f = open('test.txt', 'r')

content = f.readlines()

print(type(content))

i=1
for temp in content:
    print("%d:%s"%(i, temp))
    i+=1

f.close()

运行现象:

 

<4>读数据(readline)

#coding=utf-8

f = open('test.txt', 'r')

content = f.readline()
print("1:%s"%content)

content = f.readline()
print("2:%s"%content)


f.close()

如果一个文件很大,比如5G,试想应该怎样把文件的数据读取到内存然后进行处理呢?

示例:

#1. 获取用户要复制的文件名
old_file_name = input("请输入要复制的文件名:")

#2. 打开要复制的文件
old_file = open(old_file_name,"r")

#test.py  -----> test[复件].py
#new_file_name = "[复件]"+old_file_name
position = old_file_name.rfind(".")
new_file_name = old_file_name[:position] + "[复件]" + old_file_name[position:]

#3. 新建一个文件
#new_file = open("laowang.txt", "w")
new_file = open(new_file_name, "w")

#4. 从旧文件中读取数据,并且写入到新文件中
while True:
    content = old_file.read(1024)

    if len(content)==0:
        break

    new_file.write(content)

#5. 关闭2个文件
old_file.close()
new_file.close()

 

posted @ 2017-11-14 22:14  丰study  阅读(247)  评论(0)    收藏  举报