--- コードを実行した結果 --- 年月日なし 市町村名,1歳未満,10歳未満,10代,20代,30代,40代,50代,60代,70代,80代,90代,100歳以上,(調査中),計,,2022/03/22 ,,2022/03/22 --- csvファイルの内容 ファイル名:220322_O_843_改.csv --- 市町村名,1歳未満,10歳未満,10代,20代,30代,40代,50代,60代,70代,80代,90代,100歳以上,(調査中),計,,2022/03/22 ○○市,0,4,19,38,39,29,19,9,5,1,3,0,0,166 ✗✗市,0,4,7,15,16,9,5,2,1,0,0,0,0,59 ------ ```python コード
import csv
path_csvu8 = 'D:\105_Python\test' #utf_8ファイルの有るフォルダ
fil = path_csvu8 + '\' + '220322_O_843_改' + '.csv'
#print(fil)
fil_day_1 = fil.rfind('\')+1 #ファイル名から日付を取得1
fil_day = ',,20' + fil[fil_day_1:fil_day_1+2] + '/' + fil[fil_day_1+2:fil_day_1+4] + '/' + fil[fil_day_1+4:fil_day_1+6]
enco = 'utf-8' #'utf-8-sig' 'cp932'
with open(fil,encoding=enco) as f:
rows = f.readlines()
#print(rows) # ['あいう\n','かきく\n,....]
#print(csvfile.readlines()) # [] 空となる!
#print(rows[0]) # 先頭行
#print(rows[-2])# 最終行前行
#print(rows[-1])# 最終行
data_2 = '市町村名,1歳未満,10歳未満,10代,20代,30代,40代,50代,60代,70代,80代,90代,100歳以上,(調査中),計'
#if rows[0]== data_2 + '\n':
print('年月日なし')
str1 = '2022'
str2 = rows[0]
str3 = rows[1]
if str2 in str1: #文字列比較 https://codechacha.com/ja/python-compare-strings/
#print('年月日有り')
print(rows[0])
elif str3 in str1: #文字列比較
print('年月日有り')
print(rows[1])
else:
print('年月日なし')
print(rows[0])
print(fil_day)
あなたの回答
tips
プレビュー