반응형
Yes Cyber solution is best.
For beginners
- Read file in Read mode.
- Iterate lines by readlines() or readline()
- Use split(",") method to split line by '
- Use float to convert string value to float. OR We can use eval() also.
- Use list append() method to append tuple to list.
- Use try except to prevent code from break.
My text file is:
-34.968398,-6.487265
-34.969448,-6.488250
-34.967364,-6.492370
-34.965735,-6.582322
Code:
p = "/home/vivek/Desktop/test.txt"
result = []
with open(p, "rb") as fp:
for i in fp.readlines():
tmp = i.split(",")
try:
result.append((float(tmp[0]), float(tmp[1])))
#result.append((eval(tmp[0]), eval(tmp[1])))
except:pass
print result
Output:
$ python test.py
[(-34.968398, -6.487265), (-34.969448, -6.48825), (-34.967364, -6.49237), (-34.965735, -6.582322)]
Read file as a list of tuples, 파일읽어서 튜플 만들기
반응형
'프로그래밍 > Python' 카테고리의 다른 글
[python] Remove Elements From A Counter. counter에서 요소 삭제하기 (0) | 2020.12.17 |
---|---|
[python] How to add or increment single item of the Python Counter class (0) | 2020.12.16 |
Sublime Text 3에서 Python 프로그래밍을 하기 위해 필요한 설정을 다루고 있습니다. (0) | 2020.12.16 |
[python] style cloud 설정 (0) | 2020.12.15 |
[python] wordcloud시 불용어 지정 (0) | 2020.12.15 |