脚本宝典收集整理的这篇文章主要介绍了从文件中读取数据:读取整个文件-python进阶篇九,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
读取整个文件
要读取文件,需要一个包含几行文本的文件。下面首先来创建一个文件,它包含精确到小数点后30位的圆周率值,且在小数点后每10位处都换行:
wITh oPEn('d:/pi_digits.txt') as file_object: #返回一个表示文件的对象 contents = file_object.read() #读取文件对象的内容 PRint(contents) ''' 3.1415926535 8979323846 2643383279 '''
filename = 'd:/pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip())
通过列表一行行读取:
filename = 'd:/pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() #每次读取一行 pi_string = '' for line in lines: #循环读取列表 pi_string += line.strip() print(pi_string) print(pi_string[:10] + "...") #只读取前8位 print(len(pi_string)) #获取内容长度 ''' 3.141592653589793238462643383279 3.14159265... 32 '''
看你生日这圆周率里面吗。我一直想知道自己的生日是否包含在圆周率值中。下面来扩展刚才编写的程序,以确定某个人的生日是否包含在圆周率值的前1 000 000位中。为此,可将生日表示为一个由数字组成的字符串,再检查这个字符串是否包含在Pi_string 中:
filename = 'd:/pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip() birthday = input("Enter your birthday, in the form mmddyy: ") if birthday in pi_string: print("Your birthday appears in the First million digits of pi!") else: print("Your birthday does not appear in the first million digits of pi.") ''' Enter your birthday, in the form mmddyy: 1415 Your birthday appears in the first million digits of pi! '''
以上是脚本宝典为你收集整理的从文件中读取数据:读取整个文件-python进阶篇九全部内容,希望文章能够帮你解决从文件中读取数据:读取整个文件-python进阶篇九所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。