[python]: open(file) 文件读写(一)
一、说明
1、 os = fedora37; python版本: Python 3.11.7
2、 【python】读取文件:读取内容的数据类型是【字符串】;
3、 字符串分割函数: str.split()
4、 【python】【字符串】转化为【整数】
1 # 定义字符串
2 a = '31'
3
4
5 # 数据类型转换: [字符串] 转化为 [整数]
6 b = int(1) # b = 31
二、文件内容
1、 文件: read_file_python
1 #!/usr/bin/env python3
2
3
4 # file_name = read_file_python
5 #
6
7
8 # name: print_file_lines()
9 # function: read all lines from file; split each line by "\t";
10 def print_file_lines(fh):
11 data = []
12 lines = fh.readlines()
13 count = 0
14 print(f"\n")
15 print(f"\n[print_file_lines:\tbegin]")
16 for line in lines:
17 print(f"[line{count}]:\t{line}")
18 data.append(line.split("\t"))
19 count = count + 1
20 print(f"[print_file_lines:\tend]\n")
21 print(f"\n")
22 count = 0
23 return data
24
25
26 # name: sum_abc()
27 # function: convert string to int by 'int()'; sum = a + b + c
28 def sum_abc(data):
29 print(f"\n[sum:\tbegin]")
30 index_i = 0
31 end_i = len(data[0])-1
32
33 while ( index_i < end_i ):
34 a = int(data[0][index_i])
35 b = int(data[1][index_i])
36 c = int(data[2][index_i])
37 index_i = index_i + 1
38
39 s = a + b +c
40 print(f"a={a},\tb={b},\tc={c},\tsum={s}")
41
42 print(f"[sum:\tend]\n")
43 print(f"\n")
44
45
46
47 # run part
48 file = open("data.txt", "r")
49
50 data = []
51
52 data = print_file_lines(file)
53
54 sum_abc(data)
2、 文件: data.txt
1 [wit@fedora python]$ cat data.txt
2 1 2 3 4
3 10 20 30 40
4 100 200 300 400
5 [wit@fedora python]$
6 [wit@fedora python]$
三、运行结果
1 [wit@fedora python]$ ./read_file_python
2
3
4
5 [print_file_lines: begin]
6 [line0]: 1 2 3 4
7
8 [line1]: 10 20 30 40
9
10 [line2]: 100 200 300 400
11
12 [print_file_lines: end]
13
14
15
16
17 [sum: begin]
18 a=1, b=10, c=100, sum=111
19 a=2, b=20, c=200, sum=222
20 a=3, b=30, c=300, sum=333
21 a=4, b=40, c=400, sum=444
22 [sum: end]
23
24
25
26 [wit@fedora python]$
四、参考文档
1、 Python3 数据类型转换 -- https://www.runoob.com/python3/python3-type-conversion.html
2、 Python3 File(文件) 方法 -- https://www.runoob.com/python3/python3-file-methods.html
本文由 lnlidawei 原创、整理、转载,本文来自于【博客园】; 整理和转载的文章的版权归属于【原创作者】; 转载或引用时请【保留文章的来源信息】:https://www.cnblogs.com/lnlidawei/p/18000412