Python 3.x csv 파일 의 숫자 를 읽 고 쓰 는 방법 예제
본 고 는 주로 Python 3.x 읽 기와 쓰기 csv 파일 의 숫자 에 관 한 내용 을 소개 하고 참고 학습 을 제공 합 니 다.다음은 더 이상 말 하지 않 겠 습 니 다.상세 한 소 개 를 해 보 겠 습 니 다.
csv 파일 읽 기
파일 을 읽 을 때 str 의 목록 을 만 들 고 마지막 줄 바 꿈 자 를 삭제 합 니 다.그리고 하나씩 str 를 int 로 변환 합 니 다.
## csv
csv_file = 'datas.csv'
csv = open(csv_file,'w')
for i in range(1,20):
csv.write(str(i) + ',')
if i % 10 == 0:
csv.write('
')
csv.close()
result = []
with open(csv_file,'r') as f:
for line in f:
linelist = line.split(',')
linelist.pop()# delete:
for index, item in enumerate(linelist):
result.append(int(item))
print('
Result is
' , result)
출력:
Result is
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
디 렉 터 리 존재 여부 확인대상 디 렉 터 리 가 존재 하지 않 으 면 새 디 렉 터 리 를 만 듭 니 다.
import os
json_dir = "../dir_json/2017-04/"
if not os.path.exists(json_dir):
print("json dir not found")
os.makedirs(json_dir)
print("Create dir " + json_dir)
파일 을 쓸 때 지정 한 형식아래 코드 를 참고 하여 파일 을 열 때 utf 8 을 지정 하고 json 으로 변환 할 때 지정 합 니 다
ensure_ascii=False
import json
json_file = open(json_dir + id + '.json', 'w', encoding='utf8')
json_file.write(json.dumps(data_dict, ensure_ascii=False))
제 이 슨 파일 의 난 장 판 을 피하 십시오.함수
enumerate(iterable, start=0)
enumerate 대상 을 되 돌려 줍 니 다.iterable 은 문장,교체 기 또는 교체 대상 이 어야 합 니 다.enumerate 예제 1:
>>> data = [1,2,3]
>>> for i, item in enumerate(data):
print(i,item)
0 1
1 2
2 3
예시 2:
>>> line = 'one'
>>> for i, item in enumerate(line,4):
print(i,item)
4 o
5 n
6 e
참고:https://docs.python.org/3/library/functions.html?highlight=enumerate#enumerateclass int(x=0)
class int(x, base=10)
Integer 대상 을 되 돌려 줍 니 다.부동 소수점 에 대해 서 는 정수 로 절취 할 것 이다.
>>> print(int('-100'),int('0'),int('3'))
-100 0 3
>>> int(7788)
7788
>>> int(7.98)
7
>>> int('2.33')
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
int('2.33')
ValueError: invalid literal for int() with base 10: '2.33'
총결산이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Django | admin 백그라운드 미화 처리 JSONfield1 간단한 설명 일부 업무 수요에서 모델의 일부 필드에 대해 JSONField 적합한 업무를 사용하지만 이런 필드는 django admin에서 표시하고 수정하는 것이 직관적이고 편리하지 않기 때문에 여기에 생각을 하...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.