python 文件操作

文件操作问题和把大象放进冰箱问题类似。其核心思想为:

1. 打开和关闭文件

1、 打开文件使用的是open函数。 open函数的基本语法如下:open(file_name, [access_mode],[ buffering])

【参数解析】

  • file_name变量:是一个包含要访问的文件名称的字符串值。
  • access_mode变量:指打开文件的模式,对应有只读、写入、追加等。
  • buffering:如果buffering的值被设为0,就不会有寄存;如果buffering的值取1,访问文件时就会寄存行;如果将buffering的值设为大于1的整数,表示这就是寄存区的缓冲大小;如果取负值,寄存区的缓冲大小就是系统默认的值。


    2、关闭文件使用close函数。
    打开文件的模式:
    在这里插入图片描述
    在这里插入图片描述
path = "C:/Users/ASUS/Desktop/pythonfiletest/firstfile.txt"
f = open(path)
print(f.name)
f.close()
C:/Users/ASUS/Desktop/pythonfiletest/firstfile.txt

2. 操作文件

2.1读文件

在打开文件对象file上调用read()函数,对文件进行读取。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9F0YyjL0-1584968688639)(attachment:image.png)]

path = "C:/Users/ASUS/Desktop/pythonfiletest/firstfile.txt"
file = open(path,'r')
print(file.read())  
file.close()
first file

2.2 写文件

在打开文件对象file上调用write()函数,对文件进行读取。

2.2.1 覆盖写

path = "C:/Users/ASUS/Desktop/pythonfiletest/firstfile.txt"
file = open(path,'w')    #覆盖写
file.write("Hello file,")  
file.close()
11

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3w8Be6vy-1584968688640)(attachment:image.png)]

path = "C:/Users/ASUS/Desktop/pythonfiletest/firstfile.txt"
file = open(path,'r')
print(file.read())  
file.close()
Hello file,

2.2.2 追加写

path = "C:/Users/ASUS/Desktop/pythonfiletest/firstfile.txt"
file = open(path,'a')    #追加写
file.write("append  write.")
file.close()
14
path = "C:/Users/ASUS/Desktop/pythonfiletest/firstfile.txt"
file = open(path,'r')
print(file.read()) 
file.close()
Hello file,append  write.

2.3 读写行

Python为我们提供了readline()、readlines()和writelines()等方法用于行操作。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NoWmLf6y-1584968688640)(attachment:image.png)]

path = "C:/Users/ASUS/Desktop/pythonfiletest/secondfile.txt"
file = open(path,'r')
print(file.readline()) 
file.close()
The first line.
path = "C:/Users/ASUS/Desktop/pythonfiletest/secondfile.txt"
file = open(path,'r')
print(file.readlines())
file.close()
['The first line.
']
path = "C:/Users/ASUS/Desktop/pythonfiletest/secondfile.txt"
file = open(path,'w')    #追加写
write_str = ["The first line.
","The second line.
","The third line.
"]
file.writelines(write_str) 
file.close()
path = "C:/Users/ASUS/Desktop/pythonfiletest/secondfile.txt"
file = open(path,'r')
print(file.readlines()) 
file.close()
['The first line.
', 'The second line.
', 'The third line.
']

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dqc5pMuV-1584968688641)(attachment:image.png)]

提示: 上面的所有操作都需要在最后面关闭文件,如果每次都要这么写,就会很烦琐。Python中引入了with语句自动帮我们调用close方法。

path = "C:/Users/ASUS/Desktop/pythonfiletest/secondfile.txt"
with open(path,'r') as file:
    print(file.readlines()) 
['The first line.
', 'The second line.
', 'The third line.
']

2.4 文件重命名

Python的os模块为我们提供了rename方法,即文件重命名。使用这个方法需要导入os模块。rename方法的语法如下:os.rename(current_file_name,
new_file_name)os为导入的os模块,current_file_name为当前文件名,new_file_name为新文件名。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZXJXdk8N-1584968688641)(attachment:image.png)]

import os
os.rename("C:/Users/ASUS/Desktop/pythonfiletest/thirdfile.txt", 
          "C:/Users/ASUS/Desktop/pythonfiletest/thirdfile3.txt")

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SQz4PvUC-1584968688642)(attachment:image.png)]

2.5 删除文件

Python的os模块为我们提供了remove方法,即删除文件。使用这个方法需要导入os模块。remove方法的语法如下:os.remove(file_name)

import os 
os.remove("C:/Users/ASUS/Desktop/pythonfiletest/thirdfile3.txt")

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-StHqDFCE-1584968688642)(attachment:image.png)]

2.6 使用fileinput实现懒加载式迭代

import fileinput
path = "C:/Users/ASUS/Desktop/pythonfiletest/secondfile.txt"
for line in fileinput.input(path):
    print(f"line is :{line}")
fileinput.close()   
line is :The first line.

line is :The second line.

line is :The third line.
import fileinput
path = "C:/Users/ASUS/Desktop/pythonfiletest/secondfile.txt"
with open(path, "r") as file:
    for line in file:
        print(f"line is :{line}")
 
line is :The first line.

line is :The second line.

line is :The third line.

3. csv 文件

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uL7VrXlx-1584968688642)(attachment:image.png)]

import csv
movieinfos  = []
path = "C:/Users/ASUS/Desktop/pythonfiletest/豆瓣电影top250.csv"
with open(path, "r",encoding='UTF-8') as f:    #打开csv文件
    reader = csv.reader(f)
    head_row = next(reader)
    print(head_row)
    for row in reader:
        if reader.line_num <= 11:
             movieinfos.append(row)             #提取数据
for movieinfo in movieinfos:
    print(movieinfo)
['电影名', '评分', '导演', '主演', '年份', '国家']
['肖申克的救赎', '9.7', ' 弗兰克·德拉邦特 Frank Darabont', ' 蒂姆·罗宾斯 Tim Robbins /', '1994', '美国']
['霸王别姬', '9.6', ' 陈凯歌 Kaige Chen', ' 张国荣 Leslie Cheung / 张丰毅 Fengyi Zha', '1993', '中国大陆 中国香港']
['阿甘正传', '9.5', ' 罗伯特·泽米吉斯 Robert Zemeckis', ' 汤姆·汉克斯 Tom Hanks / ', '1994', '美国']
['这个杀手不太冷', '9.4', ' 吕克·贝松 Luc Besson', ' 让·雷诺 Jean Reno / 娜塔莉·波特曼 ', '1994', '法国']
['美丽人生', '9.5', ' 罗伯托·贝尼尼 Roberto Benigni', ' 罗伯托·贝尼尼 Roberto Beni', '1997', '意大利']
['泰坦尼克号', '9.4', ' 詹姆斯·卡梅隆 James Cameron', ' 莱昂纳多·迪卡普里奥 Leonardo', '1997', '美国']
['千与千寻', '9.3', ' 宫崎骏 Hayao Miyazaki', ' 柊瑠美 Rumi Hîragi / 入野自由 Miy', '2001', '日本']
['辛德勒的名单', '9.5', ' 史蒂文·斯皮尔伯格 Steven Spielberg', ' 连姆·尼森 Liam Neeson', '1993', '美国']
['盗梦空间', '9.3', ' 克里斯托弗·诺兰 Christopher Nolan', ' 莱昂纳多·迪卡普里奥 Le', '2010', '美国 英国']
['忠犬八公的故事', '9.3', ' 莱塞·霍尔斯道姆 Lasse Hallström', ' 理查·基尔 Richard Ger', '2009', '美国 英国']

在这里插入图片描述

4. JSON 文件

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s4PCyLMr-1584968688643)(attachment:image.png)]

import json

data = {
    'num' : 1001,
    'name' : 'xiaoming',
    'school' : 'python school'
}

# 写入 JSON 数据
with open('C:/Users/ASUS/Desktop/pythonfiletest/data.json', 'w') as f:
    json.dump(data, f)

# 读取JSON数据
with open('C:/Users/ASUS/Desktop/pythonfiletest/data.json', 'r') as f:
    data = json.load(f)
    print(data)
{'num': 1001, 'name': 'xiaoming', 'school': 'python school'}
原文地址:https://www.cnblogs.com/sinlearn/p/12665536.html