python从⽂件中读取数据
1、读取整个⽂件
不要忘记.read() 这个⽅法,
相⽐于原始⽂件,该输出唯⼀不同的地⽅是末尾多了⼀个空⾏。为何会多出这个空⾏呢?因为read()到达⽂件末尾时返回⼀个空字符串,⽽将这个空字符串显⽰出来时就是⼀个空⾏。要删除多出来的空⾏,可在函数调⽤print()中使⽤rstrip()
with open('') as file_object:
contents = ad()
print(contents.rstrip())
2、⽂件路径
2.1、相对路径
with open('text_') as file_object:
2.2、绝对路径
file_path = '/home/ehmatthes/other_files/text_files/_filename_.txt'
with open(file_path) as file_object:
注意 如果在⽂件路径中直接使⽤反斜杠,将引发错误,因为反斜杠⽤于对字符串中的字符进⾏转义。例如,对于路径"C:\path\",其中的\t将被解读为制表符。如果⼀定要使⽤反斜杠,可对路径中的每个反斜杠都进⾏转义,如"C:\\path\\to\\"。
3、逐⾏读取
如下有两个⽅法,第⼀个是在with 体内嵌套循环for来读取,,,另外⼀种⽅式⽐较好,在with代码块中将每⼀⾏读取的数据存储到列表lines中(是列表类型),然后在体外执⾏for循环,
python怎么读取文件中的数据['3.1415926535 \n', ' 8979323846 \n', ' 2643383279\n'],⽂件的每⼀⾏都带有⼀个换⾏符,执⾏print()时页会加⼀个换⾏符,所以如果不⽤rstrip()字符串末尾去空格的函数,将会每⾏之间空⼀整⾏
filename = ''
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
filename = ''
with open(filename) as file_object:
lines = adlines()
for line in lines:
print(line.rstrip())
读取⼤⽂本的前50个字符,并将该⽂本的字符总数打印出来
filename = 'pi_'
with open(filename) as file_object:
lines = adlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(f"{pi_string[:50]}")
print(len(pi_string))
输⼊⽣⽇查看是否在⽂本内容中filename = 'pi_'
with open(filename) as file_object:
lines = adlines()
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")
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论