文件打开
- with open(path,“r+”,encoding=‘UTF-8’) as f:#这两种打开方式都可以
- f = open(path, ‘r’, encoding='UTF-8)
~~ 自己试的这两种方式结果一样,f的类型相同
举例:
f = open(path, 'r', encoding='UTF-8') #以读的方式打开文件
for eachstr in f.readlines():
str=eachstr.strip() #去除每行的首位空格
if not str=='': #判断字符串是否为空
print(type(str))
print(str)
文件读取方式
- 读取文件所有行用函数readlines()
f = open(path, 'r', encoding='UTF-8') #以读的方式打开文件
for eachstr in f.readlines():
str=eachstr.strip() #去除每行的首位空格
if not str=='': #判断字符串是否为空
print(type(str))
print(str)
- 逐行读取文件用函数readline()
N = 2file = open(path, "r")#the a opens it in append mode
for i in range(N):
line=file.readline().strip()
line=float(line)
print(line)#
file.close()
数据转换
- int(str) 函数将 符合整数的规范的字符串 转换成 int 型。
num2 = "123";
num2 = int(num1);
print("num2: %d" % num2);
'''
输出 num2: 123
'''
- float(str) 函数将 符合 浮点型 的规范的字符串 转换成 float 型。
num1 = "123.12";
num2 = float(num1);
print("num2: %f" % num2);
'''
num2: 123.120000
'''
- str(num) 将 整数,浮点型转换成 字符串
num = 123;
mystr = str(num);
print ("%s" % mystr);
''' 输出 123 '''
此节选自https://www.cnblogs.com/chenfulin5/p/7813791.html