python基础文件操作
批量重命名
import os
path = 'C:/test/'
fileList = os.listdir(path)
for fileName in fileList:
usedName = path + fileName
newName = path + fileName + 'x'
os.rename(usedName,newName)
打开一个文件
file = open(path,'r',encoding='utf8',newline='',errors='ignore')
'''
必填的参数是前两个,path代表文件路径,'r'代表只读模式,当然也可以是是'w',代表只写
还有'r+','w+'读写都可以。
'a'代表不改原有文件内容情况下添加,即append
若打开模式中增加字母b,则表示二进制打开,如'rb','wb'
encoding代表编码方式
在写csv文件时一般要加上newline='',不然行与行之间会有空行
errors='ignore'代表遇到无法解析的字符自动忽略
'''
csv文件的操作
import csv
file = open('test.csv','r')
file2 = open('test2.csv','w',encoding='utf8',newline='',errors='ignore')
all_content = file.read()
line = file.readline()
lines = file.readlines()
line = line.decode('utf8','ignore')
csvWriter = csv.writer(file2)
csvWriter.writerow(['a','b','c','d'])
file.close()
file2.close()
xlsx文件的操作
import openpyxl as xl
wb = xl.load_workbook('test.xlsx')
sh1 = wb['Sheet1']
sh2 = wb['Sheet2']
for row in list(sh1.rows):
print(row[0].value)
sh2.append(['a','b','c','d'])
wb.save('test.xlsx')
wb.close()