文件处理:如何在Python中读取文件?

2021年3月12日13:07:46 发表评论 676 次浏览

本文概述

Python提供了用于创建, 写入和读取文件的内置函数。可以在python中处理的文件有两种类型, 普通文本文件和二进制文件(以二进制语言0s和1s编写)。

  • 文字档:在这种类型的文件中, 每行文本都以称为EOL(行尾)的特殊字符终止, 默认情况下, 该字符是python中的换行符(\ n)。
  • 二进制文件:在这种类型的文件中, 一行没有终结符, 并且在将数据转换为机器可理解的二进制语言后将其存储。

注意:进一步了解文件处理点击这里.

存取方式

访问模式控制着打开的文件中可能的操作类型。指的是打开文件后的使用方式。这些模式还定义了文件句柄在文件中的位置。文件句柄就像一个游标, 它定义了必须从何处读取或写入文件中的数据。读取文件的不同访问方式为–

  1. 只读(" r"):打开文本文件以供阅读。句柄位于文件的开头。如果文件不存在, 则会引发I / O错误。这也是打开文件的默认模式。
  2. 读写('r +'):打开文件进行读写。句柄位于文件的开头。如果文件不存在, 则引发I / O错误。
  3. 追加并阅读('a +'):打开文件进行读写。如果文件不存在, 则创建该文件。句柄位于文件的末尾。正在写入的数据将插入到现有数据的末尾。

注意:进一步了解访问模式点击这里.

打开文件

它是使用open()函数。此功能不需要导入任何模块。

语法如下:

File_object = open(r"File_Name", "Access_Mode")

该文件应与python程序文件位于同一目录中, 否则, 应将文件的完整地址写在文件名的位置。

注意:的[R放在文件名之前, 以防止文件名字符串中的字符被视为特殊字符。例如, 如果文件地址中有\ temp, 则\ t被视为制表符, 并且会引发无效地址的错误。 r使字符串原始, 即, 它表明该字符串没有任何特殊字符。如果文件位于同一目录中并且未放置地址, 则可以忽略r。

# Open function to open the file "MyFile1.txt"  
# (same directory) in read mode and 
file1 = open ( "MyFile.txt" , "r" ) 
    
# store its reference in the variable file1  
# and "MyFile2.txt" in D:\Text in file2 
file2 = open (r "D:\Text\MyFile2.txt" , "r+" )

在这里, 文件1创建为MyFile1的对象, 文件2创建为MyFile2的对象。

关闭文件

close()函数关闭文件并释放该文件获取的内存空间。在不再需要文件或要以其他文件模式打开文件时使用它。

语法如下:

File_object.close()
# Opening and Closing a file "MyFile.txt" 
# for object name file1. 
file1 = open ( "MyFile.txt" , "r" ) 
file1.close()

从文件读取

有三种从文本文件读取数据的方法。

  • read():以字符串形式返回读取的字节。读取n个字节, 如果未指定n, 则读取整个文件。
    File_object.read([n])
    
  • readline():读取文件的一行并以字符串形式返回。对于指定的n, 最多读取n个字节。但是, 即使n超出了行的长度, 也不会读取多于一行。
    File_object.readline([n])
    
  • readlines():读取所有行, 并将它们作为列表中的字符串元素作为每行返回。
    File_object.readlines()
    

注意: ‘\ n’被视为两个字节的特殊字符。

例子:

# Program to show various ways to 
# read data from a file. 
  
# Creating a file
file1 = open ( "myfile.txt" , "w" )
L = [ "This is Delhi \n" , "This is Paris \n" , "This is London \n" ]
  
# Writing data to a file
file1.write( "Hello \n" ) 
file1.writelines(L)
file1.close()  # to change file access modes
  
file1 = open ( "myfile.txt" , "r+" )
  
print ( "Output of Read function is " )
print (file1.read())
print ()
  
# seek(n) takes the file handle to the nth
# bite from the beginning. 
file1.seek( 0 )
  
print ( "Output of Readline function is " )
print (file1.readline())
print ()
  
file1.seek( 0 )
  
# To show difference between read and readline 
print ( "Output of Read(9) function is " )
print (file1.read( 9 ))
print ()
  
file1.seek( 0 )
  
print ( "Output of Readline(9) function is " )
print (file1.readline( 9 ))
print ()
  
file1.seek( 0 )
  
# readlines function 
print ( "Output of Readlines function is " )
print (file1.readlines())
print ()
file1.close()

输出如下:

Output of Read function is
Hello
This is Delhi
This is Paris
This is London


Output of Readline function is
Hello


Output of Read(9) function is
Hello
Th

Output of Readline(9) function is
Hello


Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

有陈述

Python中的语句用于异常处理, 以使代码更整洁, 更易读。它简化了对诸如文件流之类的公共资源的管理。与上述实现不同, 无需调用file.close()与with语句一起使用时。的与语句本身可确保正确获取和释放资源。

语法如下:

with open filename as file:
# Program to show various ways to
# read data from a file.
  
L = [ "This is Delhi \n" , "This is Paris \n" , "This is London \n" ]
  
# Creating a file
with open ( "myfile.txt" , "w" ) as file1:
     # Writing data to a file
     file1.write( "Hello \n" )
     file1.writelines(L)
     file1.close()  # to change file access modes
  
with open ( "myfile.txt" , "r+" ) as file1:
     # Reading form a file
     print (file1.read())

输出如下:

Hello
This is Delhi
This is Paris
This is London

注意:进一步了解with陈述点击这里.

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: