次のコードで問題なく表示されましたが...?
a/1.csv
csv
110,100,1000,10000
211,101,1001,10001
3
python
1import glob
2
3if __name__=="__main__":
4 for file in sorted(glob.glob("a/*.csv")):
5 file_data=open(file,'r', encoding="utf-8-sig") #ファイルを読み取りモードで開く
6 data=file_data.read() #file_dataを読み取る
7 line_data=data.split('\n')
8
9
10 for row in line_data:
11 S = row.split(',')
12
13 if len(S)==4:
14 print(S)
実行結果
bash
1$ python3 tera170375.py
2['10', '100', '1000', '10000']
3['11', '101', '1001', '10001']
4
ただしこのコードでは、以下のような最大列数が4より大きいcsvファイルでは正常に動作してくれません。
a/2.csv
csv
11,2,3,4,,
25,6,7,8,9,10
311,12,13,14,,
4
例えば次のように書けばデータが4つの行のみしっかりと表示してくれます。
python
1import glob
2
3for file in sorted(glob.glob("a/*.csv")):
4 with open(file, 'r', encoding="utf-8-sig") as f: #ファイルを読み取りモードで開く
5 for line in f.read().splitlines():
6 line_data_arr = [s for s in line.split(",") if s != ""]
7 if len(line_data_arr) == 4:
8 print(line_data_arr)
実行結果(階層a
には1.csv
、2.csv
があるとする。)
bash
1$ python3 tera170375.py
2['10', '100', '1000', '10000']
3['11', '101', '1001', '10001']
4['1', '2', '3', '4']
5['11', '12', '13', '14']
6
追記
二次元配列にしたいならば例えばこうでしょうか?
python
1import glob
2
3matrixs = dict()
4
5for file in sorted(glob.glob("a/*.csv")):
6 matrixs[file] = []
7 with open(file, 'r', encoding="utf-8-sig") as f: #ファイルを読み取りモードで開く
8 for line in f.read().splitlines():
9 line_data_arr = [int(s) for s in line.split(",") if s != ""]
10 if len(line_data_arr) == 4:
11 # print(line_data_arr)
12 matrixs[file].append(line_data_arr)
13
14for key, val in matrixs.items():
15 print(f"{key} :\n{val}\n")
実行結果例
bash
1$ python3 tera170375.py
2a\1.csv :
3[[10, 100, 1000, 10000], [11, 101, 1001, 10001]]
4
5a\2.csv :
6[[1, 2, 3, 4], [11, 12, 13, 14]]
7
追記2
一応、Python2.7系でも動くであろうコードも載せておきますが、私はPython2.7系は詳しくないので、良いコードかどうかは保証しかねます。
python
1import glob
2
3matrixs = dict()
4
5for file in sorted(glob.glob("a/*.csv")):
6 matrixs[file] = []
7 with open(file, 'r') as f:
8 for line in f.read().splitlines():
9 line = line.replace(b'\xef\xbb\xbf', "")
10 line_data_arr = [int(s) for s in line.split(",") if s != ""]
11 if len(line_data_arr) == 4:
12 # print(line_data_arr)
13 matrixs[file].append(line_data_arr)
14
15for key, val in matrixs.items():
16 print "%s :\n%s\n" % (key, str(val))
追記3
フォーマット文字列はPython3.6以降の機能でした、明記しておらずすみません。
Python3.5以前のバージョンで実行している場合はformat
メソッドを使用してください。
print("{} :\n{}\n".format(key, val))