Python3读取文件常用方法实例分析
Jun 10, 2016 pm 03:11 PM
python3
파일 읽기
本文实例讲述了Python3读取文件常用方法。分享给大家供大家参考。具体如下:
''''' Created on Dec 17, 2012 读取文件 @author: liury_lab ''' # 最方便的方法是一次性读取文件中的所有内容放到一个大字符串中: all_the_text = open('d:/text.txt').read() print(all_the_text) all_the_data = open('d:/data.txt', 'rb').read() print(all_the_data) # 更规范的方法 file_object = open('d:/text.txt') try: all_the_text = file_object.read() print(all_the_text) finally: file_object.close() # 下面的方法每行后面有‘\n' file_object = open('d:/text.txt') try: all_the_text = file_object.readlines() print(all_the_text) finally: file_object.close() # 三句都可将末尾的'\n'去掉 file_object = open('d:/text.txt') try: #all_the_text = file_object.read().splitlines() #all_the_text = file_object.read().split('\n') all_the_text = [L.rstrip('\n') for L in file_object] print(all_the_text) finally: file_object.close() # 逐行读 file_object = open('d:/text.txt') try: for line in file_object: print(line, end = '') finally: file_object.close() # 每次读取文件的一部分 def read_file_by_chunks(file_name, chunk_size = 100): file_object = open(file_name, 'rb') while True: chunk = file_object.read(chunk_size) if not chunk: break yield chunk file_object.close() for chunk in read_file_by_chunks('d:/data.txt', 4): print(chunk)
로그인 후 복사
输出如下:
hello python hello world b'ABCDEFG\r\nHELLO\r\nhello' hello python hello world ['hello python\n', 'hello world'] ['hello python', 'hello world'] hello python hello worldb'ABCD' b'EFG\r' b'\nHEL' b'LO\r\n' b'hell' b'o'
로그인 후 복사
希望本文所述对大家的Python程序设计有所帮助。
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

인기 기사
Repo : 팀원을 부활시키는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
헬로 키티 아일랜드 어드벤처 : 거대한 씨앗을 얻는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
스플릿 소설을이기는 데 얼마나 걸립니까?
3 몇 주 전
By DDD

인기 기사
Repo : 팀원을 부활시키는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
헬로 키티 아일랜드 어드벤처 : 거대한 씨앗을 얻는 방법
3 몇 주 전
By 尊渡假赌尊渡假赌尊渡假赌
스플릿 소설을이기는 데 얼마나 걸립니까?
3 몇 주 전
By DDD

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제
Gmail 이메일의 로그인 입구는 어디에 있나요?
7297
9


자바 튜토리얼
1622
14


Cakephp 튜토리얼
1342
46


라라벨 튜토리얼
1259
25


PHP 튜토리얼
1206
29



C#에서 File.ReadAllText 함수를 사용하여 텍스트 파일 내용을 읽는 방법

PHP는 파일 내용을 읽습니다: 데이터 가져오기 및 구문 분석을 구현하는 단계

ioutil.ReadFile 함수를 사용하여 파일 내용을 읽고 바이트 슬라이스를 반환합니다.

PHP에서 file_get_contents 함수를 사용하여 파일 내용을 읽는 방법

한 기사에서 Python으로 파일을 읽는 방법에 대한 모든 지식을 얻으세요.

ioutil.ReadFile 함수를 사용하여 파일 내용을 읽고 문자열을 반환합니다.

PHP의 file_get_contents() 함수를 사용하여 파일 내용 읽기
