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")

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM