📜  Python文件I / O

📅  最后修改于: 2020-12-23 05:19:37             🧑  作者: Mango


本章介绍了Python可用的所有基本I / O函数。有关更多功能,请参考标准Python文档。

打印到屏幕

产生输出的最简单方法是使用print语句,您可以在其中传递零个或多个用逗号分隔的表达式。此函数将您传递的表达式转换为字符串,并将结果写入标准输出,如下所示:

#!/usr/bin/python

print "Python is really a great language,", "isn't it?"

这会在标准屏幕上产生以下结果-

Python is really a great language, isn't it?

读取键盘输入

Python提供了两个内置函数来从标准输入中读取一行文本,默认情况下,这些输入来自键盘。这些功能是-

  • raw_input
  • 输入

raw_input函数

raw_input([prompt])函数从标准输入中读取一行,并将其作为字符串返回(删除尾随的换行符)。

#!/usr/bin/python

str = raw_input("Enter your input: ")
print "Received input is : ", str

这提示您输入任何字符串,并且它将在屏幕上显示相同的字符串。当我输入“ Hello Python!”时,其输出如下:

Enter your input: Hello Python
Received input is :  Hello Python

输入功能

input([prompt])函数等效于raw_input,不同之处在于它假定输入是有效的Python表达式并将评估结果返回给您。

#!/usr/bin/python

str = input("Enter your input: ")
print "Received input is : ", str

这将针对输入的输入产生以下结果-

Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is :  [10, 20, 30, 40]

打开和关闭文件

到目前为止,您一直在读取和写入标准输入和输出。现在,我们将看到如何使用实际数据文件。

Python提供了默认情况下处理文件所必需的基本功能和方法。您可以使用文件对象执行大多数文件操作。

开放功能

在读取或写入文件之前,必须使用Python的内置open()函数打开。此函数创建一个文件对象,该文件对象可用于调用与其关联的其他支持方法。

句法

file object = open(file_name [, access_mode][, buffering])

这是参数详细信息-

  • file_name -file_name参数是一个字符串值,其中包含您要访问的文件的名称。

  • access_mode -access_mode确定必须打开文件的模式,即读取,写入,附加等。下表中给出了可能值的完整列表。这是可选参数,默认文件访问模式为(r)。

  • 缓冲-如果将缓冲值设置为0,则不进行缓冲。如果缓冲值为1,则在访问文件时执行行缓冲。如果将缓冲值指定为大于1的整数,则将按照指示的缓冲区大小执行缓冲操作。如果为负,则缓冲区大小为系统默认值(默认行为)。

这是打开文件的不同模式的列表-

Sr.No. Modes & Description
1

r

Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

2

rb

Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

3

r+

Opens a file for both reading and writing. The file pointer placed at the beginning of the file.

4

rb+

Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.

5

w

Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

6

wb

Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

7

w+

Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

8

wb+

Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

9

a

Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

10

ab

Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

11

a+

Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

12

ab+

Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

文件对象属性

打开文件后,您只有一个文件对象,您可以获得与该文件有关的各种信息。

这是与文件对象相关的所有属性的列表-

Sr.No. Attribute & Description
1

file.closed

Returns true if file is closed, false otherwise.

2

file.mode

Returns access mode with which file was opened.

3

file.name

Returns name of the file.

4

file.softspace

Returns false if space explicitly required with print, true otherwise.

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace

这产生以下结果-

Name of the file:  foo.txt
Closed or not :  False
Opening mode :  wb
Softspace flag :  0

close()方法

文件对象的close()方法将刷新所有未写的信息并关闭该文件对象,此后将无法再进行写操作。

当文件的引用对象重新分配给另一个文件时, Python自动关闭文件。最好使用close()方法关闭文件。

句法

fileObject.close()

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

# Close opend file
fo.close()

这产生以下结果-

Name of the file:  foo.txt

读写文件

文件对象提供了一组访问方法,使我们的生活更轻松。我们将看到如何使用read()write()方法读取和写入文件。

write()方法

write()方法将任何字符串写入打开的文件。重要的是要注意, Python字符串可以具有二进制数据,而不仅仅是文本。

写()方法不换行字符(“\ n”)添加到字符串的末尾-

句法

fileObject.write(string)

此处,传递的参数是要写入打开文件的内容。

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")

# Close opend file
fo.close()

上面的方法将创建foo.txt文件,并将给定的内容写入该文件,最后将关闭该文件。如果您打开此文件,它将具有以下内容。

Python is a great language.
Yeah its great!!

read()方法

read()方法从打开的文件中读取字符串。重要的是要注意Python字符串可以具有二进制数据。除了文本数据。

句法

fileObject.read([count])

此处,传递的参数是要从打开的文件读取的字节数。此方法从文件的开头开始读取,如果缺少计数,则尝试读取尽可能多的文件,可能直到文件末尾。

我们来看一下上面创建的foo.txt文件。

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()

这产生以下结果-

Read String is :  Python is

文件位置

tell()方法告诉您文件中的当前位置;换句话说,下一次读取或写入将在文件开头起那么多字节处发生。

seek(offset [,from])方法更改当前文件位置。 offset参数指示要移动的字节数。 from参数指定要从中移动字节的参考位置。

如果from设置为0,则意味着将文件的开头用作参考位置,1意味着将当前位置作为参考位置,如果将其设置为2,则将文件的末尾用作参考位置。 。

让我们获取一个我们在上面创建的文件foo.txt

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str

# Check current position
position = fo.tell()
print "Current file position : ", position

# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10)
print "Again read String is : ", str
# Close opend file
fo.close()

这产生以下结果-

Read String is :  Python is
Current file position :  10
Again read String is :  Python is

重命名和删除文件

Python os模块提供的方法可帮助您执行文件处理操作,例如重命名和删除文件。

要使用此模块,您需要先将其导入,然后才能调用任何相关函数。

named()方法

named()方法有两个参数,当前文件名和新文件名。

句法

os.rename(current_file_name, new_file_name)

以下是重命名现有文件test1.txt的示例-

#!/usr/bin/python
import os

# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )

remove()方法

通过提供要删除的文件的名称作为参数,可以使用remove()方法删除文件。

句法

os.remove(file_name)

以下是删除现有文件test2.txt的示例-

#!/usr/bin/python
import os

# Delete file test2.txt
os.remove("text2.txt")

Python目录

所有文件都包含在各个目录中, Python也没有问题。 os模块有几种方法可以帮助您创建,删除和更改目录。

mkdir()方法

您可以使用os模块的mkdir()方法在当前目录中创建目录。您需要为此方法提供一个参数,其中包含要创建的目录的名称。

句法

os.mkdir("newdir")

以下是在当前目录中创建目录测试的示例-

#!/usr/bin/python
import os

# Create a directory "test"
os.mkdir("test")

chdir()方法

您可以使用chdir()方法更改当前目录。 chdir()方法采用一个参数,该参数是您要创建当前目录的目录的名称。

句法

os.chdir("newdir")

以下是进入“ / home / newdir”目录的示例-

#!/usr/bin/python
import os

# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")

getcwd()方法

getcwd()方法显示当前工作目录。

句法

os.getcwd()

以下是提供当前目录的示例-

#!/usr/bin/python
import os

# This would give location of the current directory
os.getcwd()

rmdir()方法

rmdir()方法删除目录,该目录作为方法中的参数传递。

在删除目录之前,应删除其中的所有内容。

句法

os.rmdir('dirname')

以下是删除“ / tmp / test”目录的示例。必须提供目录的完全限定名称,否则它将在当前目录中搜索该目录。

#!/usr/bin/python
import os

# This would  remove "/tmp/test"  directory.
os.rmdir( "/tmp/test"  )

文件和目录相关方法

有三个重要的来源,它们提供了广泛的实用程序方法来处理和操作Windows和Unix操作系统上的文件和目录。它们如下-