pythonベースファイル操作


pythonベースファイル操作
一括名の変更
import os
#    path        
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')

#   csv  
# 1.           
all_content = file.read()
# 2.   
line = file.readline()
# 3.    ,           
lines = file.readlines()
#                  
line = line.decode('utf8','ignore')

#   csv  
#     csv            newline=''
# 1.  csvWriter
csvWriter = csv.writer(file2)
# 2.         
csvWriter.writerow(['a','b','c','d'])

#     
file.close()
file2.close()

xlsxファイルの操作
#     xls  ,            xlsx  ,  openpyxl    xls
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()