python读取写入文件

In this tutorial we are going to learn about Python File Operations such as python read file, python write file, open file, delete file and copy file. Our previous tutorial was on Python Dictionary. You can find that in this link.

在本教程中,我们将学习Python文件操作,例如python读取文件,python写入文件,打开文件,删除文件和复制文件。 我们之前的教程是关于Python词典的。 您可以在此链接中找到它。

Python文件 (Python File)

In the previous tutorial we used console to take input. Now, we will be taking input using file. That means, we will read from and write into files. To do so, we need to maintain some steps. Those are

在上一教程中,我们使用控制台进行输入。 现在,我们将使用文件进行输入。 这意味着,我们将读取文件并写入文件。 为此,我们需要保持一些步骤。 那些是

  1. Open a file开启档案
  2. Take input from that file / Write output to that file从该文件获取输入/将输出写入该文件
  3. Close the file关闭档案

We will also learn some useful operations such as copy file and delete file.

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

为什么要使用文件操作 (Why Should We Use File Operation)

Suppose, you are trying to solve some problem. But you can’t solve it at once. Also, the input dataset of that problem is huge and you need to test the dataset over and over again. In that case you can use Python File Operation. You can write the dataset in a text file and take input from that text file according to your need over and over again.

假设您正在尝试解决一些问题。 但是您无法立即解决。 此外,该问题的输入数据集非常庞大,您需要反复测试数据集。 在这种情况下,您可以使用Python文件操作。 您可以将数据集写入文本文件,然后根据需要反复从该文本文件获取输入。

Again, if you have to reuse the output of your program, you can save that in a file. Then, after finishing your program, you can analysis the output of that program using another program. In these case you need Python File Operation. There may be some other cases where you may need Python File Operation.

同样,如果您必须重用程序的输出,则可以将其保存在文件中。 然后,在完成程序后,您可以使用另一个程序来分析该程序的输出。 在这种情况下,您需要Python文件操作。 在某些其他情况下,您可能需要Python文件操作。

Python打开文件 (Python Open File)

According to the previous discussion, the first step we have to perform in Python File Operation is opening that file. You can open a file by using open() function. This function take two arguments. The first one is file address and the other one is opening mode. There are some mode to open a file. Most common of them are listed below:

根据前面的讨论,我们必须在Python File Operation中执行的第一步是打开该文件。 您可以使用open()函数打开文件。 该函数有两个参数。 第一个是文件地址,另一个是打开模式。 有一些模式可以打开文件。 下面列出了其中最常见的:

  • ‘r’ : This mode indicate that file will be open for reading only'r':此模式表示文件将打开以供只读
  • ‘w’ : This mode indicate that file will be open for writing only. If file containing containing that name does not exists, it will create a new one'w':此模式表示该文件仅可打开以进行写入。 如果包含该名称的文件不存在,它将创建一个新文件。
  • ‘a’ : This mode indicate that the output of that program will be append to the previous output of that file'a':此模式指示该程序的输出将追加到该文件的先前输出
  • ‘r+’ : This mode indicate that file will be open for both reading and writing'r +':此模式表示文件将同时打开以进行读取和写入

Additionally, for Windows operating system you can append ‘b’ for accessing the file in binary. As Windows makes difference between binary file and text file.

此外,对于Windows操作系统,您可以附加“ b”以二进制形式访问文件。 由于Windows在二进制文件和文本文件之间有所不同。

Suppose, we place a text file name ‘file.txt’ in the same directory where our code is placed. Now we want to open that file. However, the open(filename, mode) function returns a file object. With that file object you can proceed your further operation.

假设我们在放置代码的目录中放置一个文本文件“ file.txt”。 现在我们要打开该文件。 但是, open(filename,mode)函数返回一个文件对象。 使用该文件对象,您可以继续进行进一步的操作。

#directory:   /home/imtiaz/code.py
text_file = open('file.txt','r')#Another method using full location
text_file2 = open('/home/imtiaz/file.txt','r')
print('First Method')
print(text_file)print('Second Method')
print(text_file2)

The output of the following code will be

以下代码的输出将是

================== RESTART: /home/imtiaz/code.py ==================
First MethodSecond Method>>>

Python读取文件,Python写入文件 (Python Read File, Python Write File)

There are some methods to read from and write to file. The following list are the common function for read and write in python. Note that, to perform read operation you need to open that file in read mode and for writing into that file, you need to open that in write mode. If you open a file in write mode, the previous data stored into that fill will be erased.

有一些读取和写入文件的方法。 以下列表是在python中进行读写的常用功能。 请注意,要执行读取操作,您需要以读取模式打开该文件,并且要写入该文件,您需要以写入模式打开该文件。 如果以写入模式打开文件,则存储在该填充中的先前数据将被删除。

  • read() : This function reads the entire file and returns a stringread():此函数读取整个文件并返回一个字符串
  • readline() : This function reads lines from that file and returns as a string. It fetch the line n, if it is been called nth time.readline():此函数从该文件中读取行并作为字符串返回。 如果第n次被调用,它将获取第n行。
  • readlines() : This function returns a list where each element is single line of that file.readlines():此函数返回一个列表,其中每个元素都是该文件的单行。
  • readlines() : This function returns a list where each element is single line of that file.readlines():此函数返回一个列表,其中每个元素都是该文件的单行。
  • write() : This function writes a fixed sequence of characters to a file.write():此函数将固定的字符序列写入文件。
  • writelines() : This function writes a list of string.writelines():此函数写入字符串列表。
  • append() : This function append string to the file instead of overwriting the file.append():此函数将字符串追加到文件中,而不是覆盖文件。

The following code will guide you to read from file using Python File Operation. We take ‘file.txt’ as our input file.

以下代码将指导您使用Python文件操作从文件中读取内容。 我们将“ file.txt”作为输入文件。

#open the file
text_file = open('/Users/pankaj/abc.txt','r')#get the list of line
line_list = text_file.readlines();#for each line from the list, print the line
for line in line_list:print(line)text_file.close() #don't forget to close the file

Again, the sample code for writing into file is given below.

同样,下面提供了用于写入文件的示例代码。

#open the file
text_file = open('/Users/pankaj/file.txt','w')#initialize an empty list
word_list= []#iterate 4 times
for i in range (1, 5):print("Please enter data: ")line = input() #take inputword_list.append(line) #append to the listtext_file.writelines(word_list) #write 4 words to the filetext_file.close() #don’t forget to close the file

Python复制文件 (Python Copy File)

We can use shutil to copy file. Below is an example showing two different methods to copy file.

我们可以使用shutil复制文件。 下面的示例显示了两种不同的文件复制方法。

import shutilshutil.copy2('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copy2.txt')#another way to copy fileshutil.copyfile('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copyfile.txt')print("File Copy Done")

Python删除文件 (Python Delete File)

We can use below code to delete a file in python.

我们可以使用以下代码删除python中的文件。

import shutil
import os#two ways to delete file
shutil.os.remove('/Users/pankaj/abc_copy2.txt')os.remove('/Users/pankaj/abc_copy2.txt')

Python关闭文件 (Python Close File)

As you see in the previous example, we used close() function to close the file. Closing the file is important.

如上例所示,我们使用close()函数关闭文件。 关闭文件很重要。

So that’s all for Python File Operation. If you have any query, please feel free to ask that in comment box.

这就是Python文件操作的全部内容。 如果您有任何疑问,请随时在评论框中提出。

Python FileNotFoundError (Python FileNotFoundError)

You will get this error if the file or directory is not present. A sample stack trace is given below.

如果文件或目录不存在,则会出现此错误。 下面给出了示例堆栈跟踪。

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

Please check the file path and correct it to get rid of FileNotFoundError.

请检查文件路径并更正它以摆脱FileNotFoundError。

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

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

翻译自: https://www.journaldev.com/14408/python-read-file-open-write-delete-copy

python读取写入文件

python读取写入文件_Python读取文件,写入文件,打开文件,删除文件,复制文件相关推荐

  1. u盘无法复制文件进去_只需一招,禁止Windows复制文件到U盘,再也不用担心你的资料被拷走!...

    现在,我们日常的生活和工作都是电脑全程陪伴,可以说是离不开电脑了. 也正是因为电脑的功能那么多,而且在保存资料方面,相比纸质资料来讲,确实有十分大的优势! 因此,有许多人都会将一些重要的个人资料或者是 ...

  2. 文件已在资源管理器中打开无法删除解决方法

    刚刚出现的问题,不知道为什么很久没有运行的百度网盘运行不了,一删重装为快,但是就出现了文件已在资源管理器中打开无法删除的苦难,重启电脑也试过了无法删除~~~ 所以有了下面的方式解决问题: 首先将你所在 ...

  3. python读取写入文件_Python读取和写入文件

    1 从文件中读取数据 1.1 读取整个文件 创建名为test的txt文本文件,添加内容如下所示: 1234567890 2345678901 3456789012 实现代码: with open('t ...

  4. python读取hdf-eos5数据_python读取与写入csv EXCEK HDF 文件

    一. 数据文件 pd指pandas简称,df指DataFrame对象. 1. csv 读取  pd.read_csv('foo.csv') 写入  df.to_csv('foo.csv') 2. HD ...

  5. python生成表格文件_python 读取excel文件生成sql文件实例详解

    python 读取excel文件生成sql文件实例详解 学了python这么久,总算是在工作中用到一次.这次是为了从excel文件中读取数据然后写入到数据库中.这个逻辑用java来写的话就太重了,所以 ...

  6. python修改yaml文件_Python读取yaml文件的详细教程

    yaml简介 1.yaml [ˈjæməl]: Yet Another Markup Language :另一种标记语言.yaml 是专门用来写配置文件的语言,非常简洁和强大,之前用ini也能写配置文 ...

  7. python读取手机文件_python 读取 网络 文件

    Python之pandas数据加载.存储 Python之pandas数据加载.存储 0. 输入与输出大致可分为三类: 0.1 读取文本文件和其他更好效的磁盘存储格式 2.2 使用数据库中的数据 0.3 ...

  8. python读取pdf文件_python读取pdf文件

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 一.安装pdfminer3k模块?二. 读取pdf文件import sysimp ...

  9. python 读取大文件_Python读取大文件

    1. 前言 前几天在做日志分析系统,需要处理几十G的文件,我尝试用原来的for line in open(filepath).readlines()处理,但停顿好久也没变化,可见占用不小的内存.在网上 ...

最新文章

  1. jupyter !wget 等系统命令使用技巧
  2. HomeZZ注册推介码
  3. MyBatis Plus Generator——基于Velocity的Controller参考模板(集成MyBatis Plus、Swagger2、自封装Response、分页)
  4. HDU 2845 Beans
  5. PHP中如何防止直接访问或查看或下载config.php文件
  6. 电力企业计量生产需求系统解决方案
  7. L2-021 点赞狂魔-PAT团体程序设计天梯赛GPLT
  8. 斯坦福CS229(吴恩达授)学习笔记(2)
  9. vue el-descriptions 样式问题
  10. VoLTE网络各节点功能介绍
  11. TaxoNN: ensemble of neural networks on stratified microbiome data for disease prediction阅读报告
  12. 电脑开机黑屏有鼠标怎么办
  13. 软件测试技术的发展史,软件测试的发展史
  14. matlab画直线段,如果要在MATLAB中绘制上题中的直线段,要求 ,则对应的MATLAB语句为____________...
  15. CouchDB查询文档
  16. 风力发电会影响气候?
  17. 【论文阅读】Region Proposal by Guided Anchoring
  18. 旅行:旅行的意义是旅行本身没有意义
  19. 有人不理解,有人不屑,到底什么是UXD
  20. java中poi导出Excel表格(前台流文件接收)

热门文章

  1. 高速收发器之8B/10B编码
  2. Docker安装NextCloud使用MySQL
  3. Dom4j中getStringValue()和getText()用法的区别
  4. BZOJ 1673 [Usaco2005 Dec]Scales 天平:dfs 启发式搜索 A*搜索
  5. JSON Web Token实际应用
  6. SharePoint 2013 激活标题字段外的Menu菜单
  7. 关于androidAsyncHttp支持https
  8. BootStrap--CSS组件
  9. android中finish和system.exit方法退出的区别
  10. BestCoder Round #4 之 Miaomiao's Geometry(2014/8/10)