目标:
掌握文件的基本操作;
了解数据维度的概念,掌握常见的数据格式。
内容:
-
编写程序,实现文件备份功能,类似于文件复制,文件名中加上了“备份”,效果图如下:
-
读取文件,打印除以#开头之外的所有行,如图:
-
编程读取存有数字的文件,对其中的数字进行排序后输出。
步骤:
题一,代码如下:
# -*- coding: utf-8 -*-
f=open("a.txt",'r',encoding='utf-8')
while True:
a=f.readline()
b="#"
if a=="":
f.close()
break
elif a[0]==b[0]:
continue
else:
print(a,end="")
运行结果:
题二,代码如下:
# -*- coding: utf-8 -*-
old_name = input("请输入你要备份的文件名: ")
index = old_name.rfind('.')
if index > 0:
postfix = old_name[index:]
new_name = old_name[:index] + postfix
old_f = open(old_name, 'rb')
new_f = open(new_name, 'wb')
content=old_f.read(1024)
for i in content:
if len(content) == 0:
break
new_f.write(content)
old_f.close()
new_f.close()
运行结果:
题三,代码如下:
# -*- coding: utf-8 -*-
list_new = ['10', '56', '3', '2', '556', '23', '45', '11', '23']
file = open('c.txt','r')
file.read()
a = file.tell()
file.close()
file = open('c.txt')
for i in range(a):
b = file.read(1)
list_new.append(b)
c = list_new.index(b)
if c < 10:
print(b,end='')
file.close()
运行结果:
心得:
(1)错误:文件中文出现乱码。
修改:在打开文件代码里添加encoding=‘utf-8’ 后运行结果中文不在乱码。
(2)错误:运行结果没有排序