python学习--文件操作

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 #encode 编码  decode 解码
 4 #GBK 编码: 全称是“《汉子内码扩展规范》” 双字节编码
 5 s = "中文字符串"
 6 bs = s.encode("utf-8")
 7 cs = s.encode("GBK")
 8 print("{} 的utf-8 编码是:{}".format(s,bs))
 9 print("{} 的gbk   编码是:{}".format(s,cs))
10 
11 #读操作:将一个文件读取到内存,并将内容输入到屏幕上
12 def main():
13     fname = input("输入文件名:")
14     infile = open(fname,"r")
15     data =infile.read()
16     print(data)
17 
18 main()
19 
20 #文件读取:read() readline() readlines()
21 #用readline()读取一个文件的前5行
22 def test():
23     fname = input("输入文件名:")
24     infile = open(fname, "r")
25     for i in range(5):
26         line = infile.readline()
27         print(line[:-1])
28 test()
29 
30 #写入文件,从内存向文件写入文件 wirte(),writelines()
31 outfile = open("outfile.txt", "w")
32 outfile.writelines(["Hello", " ", "World"])
33 outfile.close()
34 infile = open("outfile.txt", "r")
35 print(infile.read())
36 
37 '''
38 遍历文件模板
39 通用代码框架:
40 file = open(someFile, "r")
41 for line in file.readlines():
42     #处理一行文件内容
43 file.close()
44 
45 简化代码框架:
46 file = open(someFile, "r")
47 for line in file:
48     #处理一行文件内容
49 file.close()
50 '''
51 #文件拷贝实例
52 def test2():
53     #用户输入文件名
54     f1 = input("输入一个源文件:").strip()
55     f2 = input("输入一个源文件:").strip()
56 
57     #打开文件
58     infile = open(f1, "r")
59     outfile = open(f2, "w")
60 
61     #拷贝数据
62     countLines = countChars = 0
63     for line in infile:
64         countLines += 1
65         countChars += len(line)
66         outfile.write(line)
67     print(countLines, "lines add", countChars, "char copied")
68 
69     infile.close()
70     outfile.close()
71 
72 test2()

 

posted @ 2017-11-07 15:32  hayden__wang  阅读(215)  评论(0编辑  收藏  举报