一、 相关知识点
关键字with的功能是在不再需要访问文件后自动将文件关闭。所以我们在这里只是open()打开了文件,但是没有加入close()代码关闭文件,因为 Python 会在处理文件之后自动将文件关闭。
[1]全部读取
我们运行在同一目录下的 Python 文件 test.py ,代码如下:
with open('test.txt') as file_object:
contents = file_object.read()
print(contents)
[2]逐行读取
我们可以采取rstrip()方法消除空行,代码如下:
with open('test.txt') as file_object:
for line in file_object:
print(line.rstrip())
[3] 创建一个包含文件各行内容的列表
在上文中,函数open()返回的对象只在with代码块内可用,但是我们想在with代码块之外的位置使用,这就需要在with代码块内创建一个包含文本文件 test.txt 各行内容的列表。例如:
with open('test.txt') as file_object:
lines = file_object.readlines()
上述代码中readlines()方法就是从文本文件 test.txt 中依次读取每一行,并保存在lines列表中。
#输入n
n = int(input())
#函数open()返回的是打开文件的对象,
#第一行代码就是把文本文件 test.txt 打开,
#并将其对象保存在file_object变量中。
with open('src/Step1/test.txt') as file_object:
#readlines()方法就是从文本文件 test.txt 中依次读取每一行,并保存在lines列表中
lines = file_object.readlines()
count=1
for line in lines:
print(line.rstrip())
count=count+1
if count>n:break
二、spit()
F=(float)(outfile.readlines()[-1].split()[-1])
1.按某一个字符分割,如‘.’
str = ('www.google.com')
print str
结果:www.google.com
str_split = str.split('.')
print str_split
['www','google','com']
三、将列表中的str转为int
把 x 中的变量类型由字符串变为 int
x = [ ‘1’, ‘2’, ‘3’ ]
x = list(map(int, x))
四、list字符串排序
注意事项:
sort()看起来很简单,但是有一个坑,当你使用sort()结果报None的错误时,是因为sort()会直接改变原有list的顺序,直接打印list1.sort()时汇报None错误。
列表的sort排序函数
list.sort(key=None,reverse=False)
print(list)
报错!报错!!!