Python 文件操作 - 用 Python 读写文件

在本教程中,我们将研究Python中的不同文件操作,我们将讨论如何使用Python来阅读文件,写入文件,删除文件,等等。

使用 Python 中的文件

在之前的教程中,我们使用了 控制台进行输入。现在,我们将使用一个文件进行输入,这意味着我们将从中阅读并写入文件。

  1. 打开一个文件
  2. 从该文件中输入 / 输出到该文件
  3. 关闭文件

我们还将学习一些有用的操作,如复制文件和删除文件。

为什么需要 Python 中的文件操作?

在机器学习( / 社区 / 教程 / 引进到机器学习)中的大数据集时,处理文件是一个基本的必要性,因为Python是主要用于数据科学的语言,所以你需要熟悉Python提供的各种文件操作。

所以,让我们在这里探索一些Python文件操作。

1、在Python中使用Open()函数打开文件

在Python中使用文件的第一步是学习如何打开文件,您可以使用open()方法打开文件。

Python 中的 open() 函数接受两种参数:第一种是文件名和完整路径,第二种是文件开放模式。

** 下面,我列出了文件的一些常见阅读模式:**

  • 'r' : 此模式表示文件只可读
  • 'w' : 此模式表示文件只可写。如果包含该名称的文件不存在,则会创建一个新的
  • 'a' : 此模式表示该程序的输出将附加到该文件的以前的输出
  • 'r+' : 此模式表示文件将开放用于阅读和写

此外,对于Windows操作系统,您可以添加b来访问二进制文件,这是因为Windows区分了二进制文本文件和常规文本文件。

假设我们将文本文件名file.txt放置在我们的代码放置的相同目录中,现在我们想要打开该文件。

但是,函数 **open(filename, mode)**返回一个文件对象. 您可以使用该文件对象继续操作。

python open file, python file

 1#directory:   /home/imtiaz/code.py
 2text_file = open('file.txt','r')
 3
 4#Another method using full location
 5text_file2 = open('/home/imtiaz/file.txt','r')
 6print('First Method')
 7print(text_file)
 8
 9print('Second Method')
10print(text_file2)

以下代码的输出将是

1================== RESTART: /home/imtiaz/code.py ==================
2First Method
3
4Second Method
5
6>>>

阅读和写入Python中的文件

Python 提供各种方法来读和写到文件中,每个函数的行为都不同. 一个重要的事情要注意的是文件操作模式. 要读到一个文件,你需要在读或写模式中打开该文件. 在 Python 写到一个文件时,你需要在写模式下打开该文件。

以下是Python中允许您阅读和写入文件的一些功能:

  • read() : 此函数读取整个文件并返回字符串
  • readline() : 此函数读取该文件的字符串并返回字符串,如果它被称为 nth 时间
  • readlines() : 此函数返回列表,其中每个元素是该文件的单行
  • readlines() : 此函数返回列表,其中每个元素是该文件的单行
  • write() : 此函数写入文件的字符串 writelines() : 此函数写入字符串列表 append() :

让我们采取一个示例文件abc.txt,并从文件中读取单个行,用一个 for loop:

 1#open the file
 2text_file = open('/Users/pankaj/abc.txt','r')
 3
 4#get the list of line
 5line_list = text_file.readlines();
 6
 7#for each line from the list, print the line
 8for line in line_list:
 9    print(line)
10
11text_file.close() #don't forget to close the file

出发点:**

python read file

现在,我们知道如何在Python中阅读文件,让我们继续前进,在这里使用 writelines() 函数执行写操作。

 1#open the file
 2text_file = open('/Users/pankaj/file.txt','w')
 3
 4#initialize an empty list
 5word_list= []
 6
 7#iterate 4 times
 8for i in range (1, 5):
 9    print("Please enter data: ")
10    line = input() #take input
11    word_list.append(line) #append to the list
12
13text_file.writelines(word_list) #write 4 words to the file
14
15text_file.close() #don’t forget to close the file

出发点( )

python write file

在 Python 中使用 shutil() 方法复制文件

我们可以使用 shutil module来复制在Python中的文件. 这个实用程序允许我们在Python中在不同的文件上执行复制和移动操作。

1import shutil
2
3shutil.copy2('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copy2.txt')
4
5#another way to copy file
6
7shutil.copyfile('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copyfile.txt')
8
9print("File Copy Done")

在 Python 中使用 shutil.os.remove() 方法删除文件

Python 的 shutil 模块提供了 remove() 方法来从文件系统中删除文件,让我们看看我们如何在 Python 中执行删除操作。

1import shutil
2import os
3
4#two ways to delete file
5shutil.os.remove('/Users/pankaj/abc_copy2.txt')
6
7os.remove('/Users/pankaj/abc_copy2.txt')

在 Python 中使用 close() 方法关闭一个开放的文件

当您在Python中打开文件时,在您更改后关闭该文件非常重要,这将保存您之前所做的任何更改,从内存中删除该文件,并防止程序中的任何进一步阅读或写入。

合成以在Python中关闭打开的文件:

1fileobject.close()

如果我们从我们以前的例子中继续阅读文件,那么以下是如何关闭文件:

1text_file = open('/Users/pankaj/abc.txt','r')
2# some file operations here
3
4text_file.close()

此外,您可以避免手动关闭文件,如果使用 with block

6、Python FileNotFound错误

在Python中使用文件时,通常会收到FileNotFoundError,可以通过在创建文件对象时提供完整的文件路径来轻松避免。

1File "/Users/pankaj/Desktop/string1.py", line 2, in <module>
2    text_file = open('/Users/pankaj/Desktop/abc.txt','r')
3FileNotFoundError: [Errno 2] No such file or directory: '/Users/pankaj/Desktop/abc.txt'

要修复 FileNotFoundError,您只需要验证您提到的文件打开方法的路径是正确的。

结论

这些是Python上的文件操作,您可以在Python中使用更多方法,其中包括阅读CSV数据等等。 这里有关于如何使用Pandas模块(/community/tutorials/python-pandas-module-tutorial)的文章(/community/tutorials/python-csv-read-write)

我希望你喜欢阅读这篇文章! 快乐的学习:)

** 参考: **https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

Published At
Categories with 技术
Tagged with
comments powered by Disqus