跟着我们一起学 Python 30天课程-第18天-文件I / O
今天,我探讨了如何使用Python处理文件并与文件通信。这些天来,我一直在探索和分享各种Python概念以及一些使用Python编程的最佳实践。但是,我们尚未在Python之外与外界进行交互。我们的程序经常出于各种原因需要与外部世界进行通信,例如从excel,CSV或pdf文件中读取数据,转换和压缩图像,从文本文件中提取数据,从数据库中读取数据以及无数其他内容。与外部世界的交互是通过I / O或输入输出操作完成的。
文件可帮助我们将数据永久存储到系统中。当我们编写任何程序来管理某些数据时,数据会临时存储在计算机的RAM中,并且在计算机关闭时会被擦除。要永久存储数据,需要将它们存储在某种数据库或某些文件系统中,以便以后使用时可以对其进行访问。
可以根据文件的内容将文件大致分为以下两种类型:
- 二进制(也称为富文本)
- 文本
Python提供了一个内置函数open
来打开任何文件。首先需要打开任何文件才能从文件中读取数据或向其中写入一些数据。从文件中读取数据在Python中很简单。
我使用REPL作为工具来尝试本文提供的所有代码块。
打开文件
我创建了一个test.txt
包含一些虚拟内容的文件以进行测试。
test.txt
# test.txt
I am learning python.
现在,可以像这样使用Python读取此文件的内容。
main.py
content = open('test.txt')
output = content.read()
print(output) # I am learning python.
我们还可以在open
函数中打开文件时指定模式。默认情况下,该模式为“ r”或读取模式。我们还可以指定是否需要以文本或二进制模式打开文件。
Mode | Description |
---|---|
r | Opens a file for reading. (default) |
w | Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists. |
x | Opens a file for exclusive creation. If the file already exists, the operation fails. |
a | Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist. |
t | Opens in text mode. (default) |
b | Opens in binary mode. |
+ | Opens a file for updating (reading and writing) |
我们还可以在打开文件时指定编码格式。默认格式为utf-8
关闭文件
对文件执行操作后关闭文件非常重要,因为它将释放与文件关联的内存空间。
main.py
content = open('test.txt', mode='r')
output = content.read()
print(output)
content.close()
上面的块可以放在try-except finally块内。这样可以确保在执行操作时如果出现任何错误,文件将被关闭。
main.py
try:
content = open('test.txt', mode='r')
output = content.read()
print(output)
except FileNotFoundError as error:
print(f'file not found {error}')
finally:
content.close()
Python提供了更好的语法,可以使用该with
语句在文件上打开执行操作。一旦执行该操作,它将自动关闭文件。
main.py
with open('test.txt', mode='r') as content:
output = content.read()
print(output) # I am learning python.
写入文件
Python提供write
了将数据写入文件的方法。需要使用w
模式打开文件以写入文件。要注意的是,使用该w
模式会覆盖文件的内容。如果需要附加内容,则a
可以使用该模式。如果文件不存在,则在向其写入数据之前创建文件。
main.py
with open('test.txt', mode='w', encoding='utf-8') as my_file:
my_file.write('This is the first line\n') # \n is for creating a newline
my_file.write('This is the second line\n')
my_file.write('This is the third line')
main.py
with open('test.txt', mode='a', encoding='utf-8') as my_file:
my_file.write('This text will be appended')
另一种写writelines
方法是使用方法。可以提供项目列表。
main.py
with open('test.txt', mode='w', encoding='utf-8') as my_file:
my_file.writelines(['First line', '\n', 'Second Line'])
从文件读取
Python提供了许多从文件读取的方法。需要使用“ r”模式打开文件。如果我们必须一起执行读取和写入操作,则它也是“ r +”模式。该read
方法接受一个size参数,该参数基本上是它将要读取的字符计数。如果未提供大小,则它将读取整个文件。
main.py
with open('test.txt', mode='r', encoding='utf-8') as my_file:
content = my_file.read()
print(content)
有一种tell
方法可以提供当前正在读取的文件中的光标所在的位置。
该seek
方法用于将光标移到文件中的特定位置。
main.py
with open('test.txt', mode='r', encoding='utf-8') as my_file:
my_file.seek(0) # brings cursor to beginning of file
print(my_file.tell()) # prints location of cursor
content = my_file.read()
print(content)
如果文件中有很多行,一种更有效和高性能的方法是使用循环读取这些行。
main.py
with open('test.txt', mode='r', encoding='utf-8') as my_file:
for line in my_file:
print(line)
另外,Python提供了另外两种方法,readline
并且readlines.
readline
读取文件,直到到达换行符(\ n)。
readlines
返回行列表
Python文件方法
这是Python中可用的文件方法的完整列表
Method | Description |
---|---|
close() | Closes an opened file. It has no effect if the file is already closed. |
detach() | Separates the underlying binary buffer from the TextIOBase and returns it. |
fileno() | Returns an integer number (file descriptor) of the file. |
flush() | Flushes the write buffer of the file stream. |
isatty() | Returns True if the file stream is interactive. |
read(n) | Reads at most n characters from the file. Reads till end of file if it is negative or None. |
readable() | Returns True if the file stream can be read from. |
readline(n=-1) | Reads and returns one line from the file. Reads in at most n bytes if specified. |
readlines(n=-1) | Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified. |
seek(offset,from=SEEK_SET) | Changes the file position to offset bytes, in reference to from (start, current, end). |
seekable() | Returns True if the file stream supports random access. |
tell() | Returns the current file location. |
truncate(size=None) | Resizes the file stream to size bytes. If size is not specified, resizes to current location. |
writable() | Returns True if the file stream can be written to. |
write(s) | Writes the string s to the file and returns the number of characters written. |
writelines(lines) | Writes a list of lines to the file. |
很酷的练习
让我们尝试构建一个翻译程序,该程序可以读取英语内容的文件,并使用其他语言创建该文件的新翻译版本。
在本练习中,我们将使用来自PyPI的外部Python包Translate。借助此软件包,我们可以进行离线翻译!
首先,需要安装此软件包。由于我正在使用REPL,因此将其添加到REPL的“包”部分。pip
如果使用本地项目,则可以在终端中使用进行安装。
将创建一个名为的文件quote.txt
,并用鼓舞人心的引号填充它:
quote.txt
If you can't make it good, at least make it look good. - Bill Gates
现在让我们生成此报价的两个翻译版本。一个以西班牙语命名quote-es.txt
,带有文件名,另一个以法语命名,带有文件名quote-fr.txt
main.py
from translate import Translator
spanish_translate = Translator(to_lang="es")
french_translate = Translator(to_lang="fr")
try:
with open('quote.txt', mode='r') as quote_file:
# read the file
quote = quote_file.read()
# do the translations
quote_spanish = spanish_translate.translate(quote)
quote_french = french_translate.translate(quote)
# create the translated files
try:
with open('quote-es.txt', mode='w') as quote_de:
quote_de.write(quote_spanish)
with open('quote-fr.txt', mode='w') as quote_fr:
quote_fr.write(quote_french)
except IOError as error:
print('An error ocurred')
raise (error)
except FileNotFoundError as error:
print('File not found')
raise (error)
这将生成两个翻译后的文件,报价自动翻译。太酷了!
内置模块处理文件
Python提供了一个内置模块,作为其标准库(称为)的一部分pathlib
。它提供了各种方便的类,这些类使用适合于不同操作系统的语义来表示文件系统路径。v3.4中引入了此模块。处理大量目录时使用此软件包是有益的。
这里是与pathlib
模块相关的一些资源,并有详尽的解释。
- https://realpython.com/python-pathlib/
- https://docs.python.org/3/library/pathlib.html
- https://www.geeksforgeeks.org/pathlib-module-in-python/
pathlib
在将来的几天中,在构建项目时将明确使用模块。
今天就这些。明天我计划探索在Python中使用正则表达式及其用例。
跟着我们一起学 Python 30天课程目录:
- 跟着我们一起学 Python 30天课程-第30天-免费Python资源
- 跟着我们一起学 Python 30天课程-第29天-自动化测试
- 跟着我们一起学 Python 30天课程-第28天-ML和数据科学II
- 跟着我们一起学 Python 30天课程-第27天-ML和数据科学I
- 跟着我们一起学 Python 30天课程-第26天-机器学习基础
- 跟着我们一起学 Python 30天课程-第25天-Web 开发进阶
- 跟着我们一起学 Python 30天课程-第24天-Web开发基础
- 跟着我们一起学 Python 30天课程-第23天-网页爬虫
- 跟着我们一起学 Python 30天课程-第22天-脚本额外功能Scripting Extras
- 跟着我们一起学 Python 30天课程-第21天-脚本编写基础
- 跟着我们一起学 Python 30天课程-第20天-调试和测试
- 跟着我们一起学 Python 30天课程-第19天-正则表达式
- 跟着我们一起学 Python 30天课程-第18天-文件I / O
- 跟着我们一起学 Python 30天课程-第17天-外部模块External Modules
- 跟着我们一起学 Python 30天课程-第16天-模块基础Module Basics
- 跟着我们一起学 Python 30天课程-第15天-生成器Generators
- 跟着我们一起学 Python 30天课程-第14天-错误处理Error Handling
- 跟着我们一起学 Python 30天课程-第13天-Decorators
- 跟着我们一起学 Python 30天课程-第12天-Lambda Expressions & Comprehensions
- 跟着我们一起学 Python 30天课程-第11天-函数编程Functional Programming基础
- 跟着我们一起学 Python 30天课程-第10天-OOP Missing Pieces
- 跟着我们一起学 Python 30天课程-第9天-OOP Pillars
- 跟着我们一起学 Python 30天课程-第8天-OOP基础知识
- 跟着我们一起学 Python 30天课程-第7天-开发环境搭建(Developer Environment)
- 跟着我们一起学 Python 30天课程-第6天-循环II和函数(Loops II & Functions)
- 跟着我们一起学 Python 30天课程-第5天-条件和循环I(Conditions & Loops I)
- 跟着我们一起学 Python 30天课程-第4天-数据类型III(Data Types III)
- 跟着我们一起学 Python 30天课程-第3天-数据类型II(Data Types II)
- 跟着我们一起学 Python 30天课程-第2天-数据类型I(Data Types I)
- 跟着我们一起学 Python 30天课程-第1天-简介
1. 本站资源转自互联网,源码资源分享仅供交流学习,下载后切勿用于商业用途,否则开发者追究责任与本站无关!
2. 本站使用「署名 4.0 国际」创作协议,可自由转载、引用,但需署名原版权作者且注明文章出处
3. 未登录无法下载,登录使用金币下载所有资源。
IT小站 » 跟着我们一起学 Python 30天课程-第18天-文件I / O
常见问题FAQ
- 没有金币/金币不足 怎么办?
- 本站已开通每日签到送金币,每日签到赠送五枚金币,金币可累积。
- 所有资源普通会员都能下载吗?
- 本站所有资源普通会员都可以下载,需要消耗金币下载的白金会员资源,通过每日签到,即可获取免费金币,金币可累积使用。