python保存内容到文件(text、json、csv)

在开发人员的日常中,将数据保存到文件是最常见的编程任务之一。

通常,程序需要一些输入并产生一些输出。在许多情况下,我们希望将这些结果持久化。我们可能会发现自己将数据保存到一个文件中以供以后处理——从我们浏览的网页,简单的表格数据转储,我们用于报告,机器学习和训练或在应用程序运行时进行日志记录——我们依赖于应用程序写入文件,而不是手动进行。

Python允许我们保存各种类型的文件,而不必使用第三方库。

 

文件打开:

当打开一个文件时,你需要文件名——一个可以是相对路径或绝对路径的字符串。第二个参数是模式,它决定了您可以对打开的文件执行的操作。

my_data_file = open('data.txt', 'w')
  • r - 默认模式、读文件;(default mode) open the file for reading
  • w - 打开文件并写入,注意如果文件中有内容会被覆盖;open the file for writing, overwriting the content if the file already exists with data
  • x - 创建文件、如果文件已有则忽略;creates a new file, failing if it exists
  • a - 打开文件进行写入,并将新内容附加在原来内容之后;open the file for writing, appending new data at the end of the file's contents if it already exists
  • b - 将文件以二进制的形式写入,而非文本格式;write binary data to files instead of the default text data
  • + - allow reading and writing to a mode

关闭一个文件:

my_data_file.close()

更常见的模式是使用with模式:

with open('data.txt', 'w') as my_data_file:
    # TODO: write data to the file
# After leaving the above block of code, the file is closed

保存文本文件:

with open('do_re_mi.txt', 'w') as f:
    f.write('Doe, a deer, a female deer\n')
    f.write('Ray, a drop of golden sun\n')

一次写入多行数据:

with open('browsers.txt', 'w') as f:
    web_browsers = ['Firefox\n', 'Chrome\n', 'Edge\n']
    f.writelines(web_browsers)
with open('browsers.txt', 'w') as f:
    web_browsers = ['Firefox\n', 'Chrome\n', 'Edge\n']
    f.writelines("%s\n" % line for line in web_browsers)

写入CSV文件:

import csv

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
sales = ['10', '8', '19', '12', '25']

with open('sales.csv', 'w') as csv_file:
    csv_writer = csv.writer(csv_file, delimiter=',')
    csv_writer.writerow(weekdays)
    csv_writer.writerow(sales)

写入json文件:

import json

my_details = {
    'name': 'John Doe',
    'age': 29
}

with open('personal.json', 'w') as json_file:
    json.dump(my_details, json_file)

 

保存文件在我们编写的许多程序中都可以派上用场。要用Python编写文件,我们首先需要打开该文件,并确保稍后关闭它。

最好使用with关键字,这样当我们写入文件时,文件就会自动关闭。

我们可以使用write()方法将字符串的内容放到文件中,或者使用writelines()如果有一个文本序列要放到文件中。

对于CSV和JSON数据,我们可以使用Python提供的特殊函数,在文件打开时将数据写入文件。