python 从文件中读取数据
1、读取整个文件
不要忘记.read() 这个方法,
相比于原始文件,该输出唯一不同的地方是末尾多了一个空行。为何会多出这个空行呢?因为read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。要删除多出来的空行,可在函数调用print()中使用rstrip()
with open('pi_digits.txt') as file_object: contents = file_object.read() print(contents.rstrip())
2、文件路径
2.1、相对路径
with open('text_files/filename.txt') as file_object:
2.2、绝对路径
file_path = '/home/ehmatthes/other_files/text_files/_filename_.txt' with open(file_path) as file_object:
注意 如果在文件路径中直接使用反斜杠,将引发错误,因为反斜杠用于对字符串中的字符进行转义。例如,对于路径"C:\path\to\file.txt",其中的\t将被解读为制表符。如果一定要使用反斜杠,可对路径中的每个反斜杠都进行转义,如"C:\\path\\to\\file.txt"。
3、逐行读取
如下有两个方法,第一个是在with 体内 嵌套循环for来读取,,,另外一种方式比较好,在with代码块中 将每一行读取的数据存储到列表lines中(是列表类型),然后在体外执行for循环,
['3.1415926535 \n', ' 8979323846 \n', ' 2643383279\n'],文件的每一行都带有一个换行符,执行print()时页会加一个换行符,所以如果不用rstrip()字符串末尾去空格的函数,将会每行之间空一整行
filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip())
filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())
读取大文本的前50个字符,并将该文本的字符总数打印出来
filename = 'pi_million_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.strip() print(f"{pi_string[:50]}") print(len(pi_string))
输入生日查看是否在文本内容中
filename = 'pi_million_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.strip() birthday = input("input your birthday: ") if birthday in pi_string: print(f"Your birthday in list") else: print(f"Your birthday does not in list")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了