如何在Python中创建,读取,追加和写入文件
在本教程中,我们将学习如何使用文件,以便程序可以快速分析大量数据。我们将主要与open()函数一起使用以使用Python编程语言创建,读取,追加或者写入文件。
如何创建一个空文件
如何读取文本文件的内容
如何写文件
如何将新内容添加到现有文件
我们将如何在GUI环境中写入文件?
让我们以非常基本的外行术语来理解。我假设大多数人都具有Windows环境的经验,因此要使用图形界面在某些记事本中写入文件,我们会怎么做?
创建一个新的文本文件(如果尚不存在)
打开文件进行编辑
将数据写入文件
保存文件
完成后关闭文件
在使用文本文件执行读/写操作时,我们在Python中采用了类似的方法。
使用open()函数打开文件的语法
要使用open()函数打开文件,请向其传递一个字符串路径,该路径指示我们要打开的文件。它可以是绝对路径,也可以是相对路径。
语法1:与open()一起使用
在Python中打开文件的syntax
为:
with open('<PATH/OF/FILE>','<MODE>') as <FILE_OBJECT>:
open()函数需要一个参数:我们要打开的文件的名称。
Python在存储当前正在执行的程序的目录中查找此文件。
因此,建议对提供的文件使用绝对或者相对路径。
open()函数返回一个代表文件的" FILE_OBJECT"。根据选择,该" FILE_OBJECT"可以是任何变量。
接下来,我们必须分配一个" MODE"来打开文件。
我们可以从以下可用的Python模式中进行选择:
模式 | 是什么 |
---|---|
“x” | 创建新的空文件 |
“r' | 文件必须已经存在,并且它以只读模式打开。 |
“w” | 文件以只读写模式打开。如果文件已存在,则文件将被截断为零长度,并覆盖该文件,或者如果不存在,则会创建该文件。 |
“a' | 文件以只读写模式打开。如果文件已经存在,则文件将保持完整,并且我们编写的数据将添加到文件中已经存在的内容中。如果文件不存在,则创建该文件。 |
“r+”;文件必须已存在,并且已打开以进行读写 | |
“w+”;打开文件进行读写。如果文件已经存在,或者在不存在时创建文件,则会截断并覆盖该文件。 | |
“a+”;打开文件进行读写。如果文件已经存在,则文件将保持完整,并且我们编写的数据将添加到文件中已经存在的内容中。如果文件不存在,则创建该文件。 |
我们还可以选择在以下位置打开文件:
文字模式(t)
二进制模式(b)
提示:
因此,如果我们希望以"写+二进制"模式打开文件,则应指定" wb"。默认情况下," open()"将以文本模式打开文件,因此我们不必在每次对文本文件使用" open()"时都提供" t"。
语法2:使用open()和close()
另外,我们也可以通过直接使用
open()
函数并将其分配给FILE_OBJECT
来打开文件。这个" FILE_OBJECT"可以再次是任何变量。
我们可以使用与上面讨论的格式相同的相同模式集。
唯一的区别是,一旦处理完文件,我们必须提供
close()
函数。
FILE_OBJECT = open('<PATH/OF/FILE>','<MODE>') # read write operations FILE_OBJECT.close()
我应该使用哪种语法(与open()或者open()一起使用)?
一旦不再需要访问文件时,关键字
close()
就会关闭文件。我们必须已经注意到,在此程序中使用的是我们所谓的" open()",而不是" close()"。
我们可以分别通过调用open()和close()函数来打开和关闭文件,但是如果程序中的错误阻止了执行close()方法,则该文件可能永远不会关闭。
这看似微不足道,但是不正确地关闭文件可能会导致数据丢失或者损坏。
而且,如果我们在程序中过早调用
close()
,就会发现自己尝试使用关闭的文件(我们无法访问的文件),这会导致更多错误。确切地知道何时应该关闭文件并不总是很容易,但是使用
with open()
python会为我们解决这个问题。我们所需要做的就是打开文件并根据需要对其进行"处理",并相信Python将在with块执行完后自动将其关闭。
如何创建一个空文件
示例1:使用touch()
理想情况下,如果我们只是想创建一个空文件,则可以使用如下所示的touch()
函数或者使用touch
命令调用subprocess.call:
#!/usr/bin/env python3 from pathlib import Path Path('/tmp/file.txt').touch()
这将在/tmp /
下创建一个空文件。
# python3 file_operator.py
验证是否创建了新文件:
# ls -l /tmp/file.txt -rw-r--r-- 1 root root 0 May 19 11:08 /tmp/file.txt
示例2:与open()一起使用
但是由于本教程是关于open()
和with open()
的,因此我们将这些功能与不同模式结合使用来创建一个空文件。接下来,我们将使用with open()
,如下所示。其中我使用file_object
作为FILE_OBJECT
的变量名,我们可以使用任何其他变量。
#!/usr/bin/env python3 with open('/tmp/file.txt', 'x') as file_object: pass
其中我们将使用x来创建/tmp/file.txt
,这意味着"创建一个空文件"。
执行脚本:
Python创建文件失败(如果文件存在)
该脚本失败,并显示错误文件存在。
说明:
将x与open()
一起使用时,我们可以创建一个空文件,前提是该文件不存在。如果提供的文件已经存在,则创建操作将失败。
因此,我们将删除退出的/tmp/file.txt
并重新执行脚本:
# rm -f /tmp/file.txt
# python3 file_operator.py
因此,现在就创建了新文件。
# ls -l /tmp/file.txt -rw-r--r-- 1 root root 0 May 19 11:15 /tmp/file.txt
示例3:使用open()
我们还可以使用以下格式的open()
函数:
#!/usr/bin/env python3 file_object = open('/tmp/file.txt', 'x') file_object.close()
并且这还将继续并创建一个空文件/tmp/file.txt
(如果尚不存在)
如何读取文件内容
现在我们有了File object
,我们可以开始读取它了。可以采用不同的方式来读取文件的内容,我们将在本节中通过不同的示例进行学习:
读取文件内容的基本语法为:
with open('<PATH/OF/FILE>','r') as <FILE_OBJECT>: FILE_OBJECT.read()
或者
FILE_OBJECT = open('<PATH/OF/FILE>','r') FILE_OBJECT.read()
这里我们使用" r",即带有open()
函数的读取模式。要实际读取内容,我们需要将read()
与文件对象值一起使用。
在下面的示例中,我将使用此dataFile
测试我们的read()
操作。
# cat dataFile some date-1 5 some data-2 10 some data-3 15
示例1:以字符串形式读取文件的内容
如果我们想读取文件的全部内容作为字符串值,请使用File对象的read()
方法。
#!/usr/bin/env python3 # Open the file in read mode file_object = open('dataFile', 'r') # Store the content of file in content var. # You can use any name for this variable content = file_object.read() # print the content print(content) # Close the file object of file file_object.close()
执行脚本:
# python3 file_operator.py some date-1 5 some data-2 10 some data-3 15
说明:
与原始文件相比,我们可能会在此脚本的输出中观察到额外的换行符。空行出现是因为read()
到达文件末尾时将返回一个空字符串。该空字符串显示为空白行。如果要删除多余的空白行,可以在对print()的调用中使用rstrip()
:
因此,要从最后一行删除换行符,我们的代码应如下所示:
#!/usr/bin/env python3 # Open the file in read mode file_object = open('dataFile', 'r') # Store the content of file in content var. # You can use any name for this variable content = file_object.read() # print the content print(content.rstrip()) # Close the file object of file file_object.close()
现在,这不应在打印输出的末尾添加任何新行。
与open()
函数一起使用
#!/usr/bin/env python3 # Open the file in read mode with open('dataFile', 'r') as file_object: # Store the content of file in content var. # You can use any name for this variable content = file_object.read() # print the content print(content.rstrip())
该脚本的输出:
# python3 file_operator.py some date-1 5 some data-2 10 some data-3 15
示例2:逐行读取文件的内容
在阅读文件时,我们通常会需要检查文件的每一行。我们可能正在文件中寻找某些信息,或者我们想要以某种方式修改文件中的文本。
我们可以在文件对象上使用" for"循环来一次检查文件中的每一行
在此示例中,我们将文件及其路径分配给
filename
变量我们再次使用
with
语法让Python正确打开和关闭文件。要检查文件的内容,我们通过遍历文件对象来遍历文件中的每一行
#!/usr/bin/env python3 filename = '/root/scripts/dataFile' # Open the file in read mode with open(filename, 'r') as file_object: for line in file_object: print(line)
此脚本的输出。当我们打印每一行时,我们会发现更多的空白行。之所以出现这些空白行,是因为文本文件中每行的末尾都包含一个不可见的newline
字符。每次调用print函数时,都会添加自己的" newline"字符,因此每行末尾都有两个" newline"字符,一个来自文件,一个来自" print()"。
# python3 file_operator.py some date-1 5 some data-2 10 some data-3 15
在print()
调用的每一行上使用rstrip()
消除了这些多余的空白行。使用rstrip()
更新了脚本
#!/usr/bin/env python3 filename = '/root/scripts/dataFile' # Open the file in read mode with open(filename, 'r') as file_object: for line in file_object: print(line.rstrip())
该脚本的输出:
# python3 file_operator.py some date-1 5 some data-2 10 some data-3 15
示例3-将文件中的内容存储在列表中(readlines())
当使用with时,由open()返回的文件对象仅在包含它的with块内可用。
如果要保留对with块之外的文件内容的访问权限,可以将文件的行存储在块内的列表中,然后使用该列表。
我们可以立即处理文件的某些部分,并将某些处理推迟到以后在程序中进行。
#!/usr/bin/env python3 filename = '/root/scripts/dataFile' # Open the file in read mode and store the content in file_object with open(filename, 'r') as file_object: # Use readlines() to store the content in lines variable as a List lines = file_object.readlines() # Use for loop outside the scope of with open() and # print the content of lines for line in lines: print(line.rstrip())
该脚本的输出:
# python3 file_operator.py some date-1 5 some data-2 10 some data-3 15
示例4-执行简单的计算
现在,当我们知道如何在python中读取文件时,让我们利用它执行一些基本的添加操作。在此脚本中,我们将计算第三列的值并打印total
。我已经在脚本的注释部分解释了每一行
filename = '/root/scripts/dataFile' total = 0.0 # Open the file in write mode and store the content in file_object with open(filename, 'r') as file_object: for line in file_object: # Split the line based on whitespace character parts = line.split( ) # Convert the value into integer of 3rd column parts[2] = int(parts[2]) # Add all the values from third column total += parts[2] # Print the total print(total)
该脚本的输出:
# python3 file_operator.py 30.0
示例5:使用格式读取和对齐数据
在这个例子中,我们将从datafile中读取内容,并使用print格式,使该文件的内容对齐。我已经添加了足够的注释来解释代码的每一行。
#!/usr/bin/env python3 filename = '/root/scripts/dataFile' # Open the file in write mode and store the content in file_object with open(filename, 'r') as file_object: # This section would be executed only if with is successful # Print a formatted string with First and Second is left aligned with a value of 10 # and Third is right aligned with a value of 5 print(f'{"First":<10}{"Second":<10}{"Third":>5}') for line in file_object: # Split the line based on whitespace character parts = line.split( ) # Arrange the line content with the provided format # as we had used earlier for alignment print(f'{parts[0]:<10}{parts[1]:<10}{parts[2]:>5}')
如何写文件
要将文本写入文件,我们需要使用第二个参数w调用open(),即,写入模式告诉Python我们要写入文件。
我们应谨慎使用" w",因为它会"覆盖文件的现有内容"。
如果提供的文件不存在,
w
将创建一个新文件并开始写入该文件如果文件已经存在一些数据,
w
将覆盖内容,然后将数据写入该文件。
示例1:写入一个空文件
我们可以使用open()或者open(),因为open()更灵活,更现代,我将在所有示例中仅使用它。但是我希望我们已经了解了open()的语法,因此可以相应地移植它们。
在本示例中,我们将创建一个新文件(/tmp/someData.txt
),并将一些内容放入该文件中
#!/usr/bin/env python3 filename = '/tmp/someData.txt' # Open the file in write mode and store the content in file_object with open(filename, 'w') as file_object: file_object.write("Python write to file\n")
执行此脚本:
# python3 file_operator.py
如预期的那样,该程序没有终端输出,但是我们可以检查是否创建了/tmp/someData.txt并验证其内容:
# cat /tmp/someData.txt Python write to file
说明:
Python只能将字符串写入文本文件。如果要将数字数据存储在文本文件中,则必须先使用str()函数将数据转换为字符串格式。
示例2:编写多行
如果我们观察前面的示例,则我在打印字符串的末尾添加了\ n。 write()函数不会在我们编写的文本中添加任何换行符。因此,如果我们在不包含换行符的情况下编写了多行内容,则文件的外观可能不符合期望。因此,我们将使用\ n新行字符将多行写入文本文件。
#!/usr/bin/env python3 filename = '/tmp/someData.txt' # Open the file in write mode and store the content in file_object with open(filename, 'w') as file_object: file_object.write("First line\n") file_object.write("Second line\n")
执行脚本并观察/tmp/someData.txt
的内容
# cat /tmp/someData.txt First line Second line
示例3:执行搜索并修改文件内容
在此示例中,我们将执行一些搜索,然后修改文件的内容,然后将其存储到单独的文件中。我们已经有一个具有以下内容的dataFile
# cat /root/scripts/dataFile some date-1 5 some data-2 10 some data-3 15
我们希望在第三列的第二行中将值替换为10到20,因此我们将使用带有open()函数的读写方法,并将更新后的内容写入新文件/tmp/temp_file.txt中。
#!/usr/bin/env python3 in_f = '/root/scripts/dataFile' out_f = '/tmp/temp_file.txt' # Open the file in read mode and store the content in input_f input_f = open(in_f, 'r') # Open the file in write mode and store the content in output_f output_f = open(out_f, 'w') # Access both the files using with with input_f, output_f: # Run a loop for each line in the input file for line in input_f: # Split the content using whitespace character and store each field in first, second and third first, second, third = line.split( ) # If third column doesn't contain 10 then just add the line in output file if third != '10': output_f.write(line) else: # if third column contains 10, then replace the whole line # with provided list new_line = ' '.join([first, second, '20']) # Add a new line at the end of above List output_f.write(new_line + "\n")
该脚本的输出:
# cat /tmp/temp_file.txt some date-1 5 some data-2 20 some data-3 15
因此,第二行的第三列已正确更新为新值20
提示:
我们可以使用fileinput在同一文件中执行搜索和替换,而当前不在本教程范围之内。
我可能会写另一个关于这个主题的教程。
如何将内容添加到文件
如果要向文件中添加内容而不是覆盖现有内容,则可以在"追加"模式下打开文件。
当我们以"追加"模式打开文件时,Python不会在返回文件对象之前清除文件的内容。
我们写入文件的所有行都会添加到文件末尾。
如果该文件尚不存在,Python将为我们"创建一个空文件"。
示例1:将数据追加到现有文件
我们将使用现有的/tmp/someData.txt
添加新行,使用open和a
,即追加模式。
#!/usr/bin/env python3 filename = '/tmp/someData.txt' # Open the file in append mode and append the new content in file_object with open(filename, 'a') as file_object: file_object.write("Third line\n")
我们执行此脚本并验证/tmp/someData.txt
的内容
# python3 file_operator.py
第三行添加到我们的现有文件中
# cat /tmp/someData.txt First line Second line Third line
追加与写作
如果文件已经包含信息,并且我们以写模式打开它,然后对其进行写操作,则新内容实际上将覆盖(替换)文件中已有的任何内容。不可撤消。因此,如果文件的内容很重要,则要确保不要犯该错误。要将内容添加到文件中,请在添加(a)模式下打开文件,然后使用.write写入文件。