这篇文章主要讲解了“python文件流读写如何操作”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“python文件流读写如何操作”吧!
使用try进行异常发现,使用while检测文件末尾进行读取
file_to_read = raw_input("Enter file name of tests (empty string to end program):")
try:
infile = open(file_to_read, 'r')
while file_to_read != " ":
file_to_write = raw_input("Enter output file name (.csv will be appended to it):")
file_to_write = file_to_write + ".csv"
outfile = open(file_to_write, "w")
readings = (infile.readline())
print readings
while readings != 0:
global count
readings = int(readings)
minimum = (infile.readline())
maximum = (infile.readline())
使用for遍历读取的每一行,进行一次性的读取和输入
下面调用的程序读取的数据是
result = list()
with open('../test/parameter.txt') as f:
for line in f.readlines():
temp = list()
# 逐个遍历对应每一行元素,将之转为对应的数据
b = line.strip(",][").split(',')
if(len(b) >= 5):
b.pop()
for a in b:
a = a.replace('[','').replace(']','')
temp.append(float(a))
result.append(temp)
#print("中途打印的temp是",temp)
#print("加入到result中的结果是",result)
删除字符串首尾的多余字符串strip()
# 删除字符串中多余字符
def string_remove():
str1 = ' abc
'
print str1.strip() # abc
str2 = '----abcdf++++'
print str2.strip('-+') # abcdf
replace函数,删除字符串中某一个所有的字符串
ss = 'old old string'
ret = ss.replace('old', 'new', 1)
print(ret)
sub函数,同时删除多个字符串,这里使用了正则表达式
str2 = '
abc
wrt22 666 ' # 删除字符串中的所有
,
import re
print(re.sub('[
]','',str2)) # abcwrt22666
感谢各位的阅读,以上就是“python文件流读写如何操作”的内容了,经过本文的学习后,相信大家对python文件流读写如何操作这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。