티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How do you read a file into a list in Python?
Python에서 파일을 리스트로 읽는 방법은 무엇인가요?
문제 내용
I want to prompt a user for a number of random numbers to be generated and saved to a file. He gave us that part. The part we have to do is to open that file, convert the numbers into a list, then find the mean, standard deviation, etc. without using the easy built-in Python tools.
사용자에게 생성할 임의의 숫자의 수를 묻고 파일에 저장하도록 요청하는 것이 목표입니다. 그 부분은 이미 해결했습니다. 우리가 해야 할 부분은 그 파일을 열어 숫자를 리스트로 변환한 다음 평균, 표준 편차 등을 쉽게 제공되는 Python 도구를 사용하지 않고 계산하는 것입니다.
I've tried using open
but it gives me invalid syntax (the file name I chose was "numbers" and it saved into "My Documents"
automatically, so I tried open(numbers, 'r')
and open(C:\name\MyDocuments\numbers, 'r')
and neither one worked).
저는 open을 사용해 보았지만 구문 오류가 발생했습니다. (제가 선택한 파일 이름은 "numbers"이며 자동으로 "내 문서"에 저장되었으므로 open(numbers, 'r') 및 open(C:\name\MyDocuments\numbers, 'r')를 시도해 보았으나 둘 다 작동하지 않았습니다).
높은 점수를 받은 Solution
with open('C:/path/numbers.txt') as f:
lines = f.read().splitlines()
this will give you a list of values (strings) you had in your file, with newlines stripped.
이것은 파일에 포함된 값 (문자열)을 새 줄로 분리하여 리스트로 반환합니다.
also, watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward slashes or double backslashes instead.
또한, 윈도우 경로 이름에서 역 슬래시를 조심하세요. 이들은 문자열에서 이스케이프 문자로 취급되기 때문입니다. 대신 슬래시나 두 번의 역 슬래시를 사용할 수 있습니다.
가장 최근 달린 Solution
To summarize a bit from what people have been saying:
사람들이 말한 내용을 요약하자면:
f=open('data.txt', 'w') # will make a new file or erase a file of that name if it is present
f=open('data.txt', 'r') # will open a file as read-only
f=open('data.txt', 'a') # will open a file for appending (appended data goes to the end of the file)
If you wish have something in place similar to a try/catch
try/catch와 비슷한 기능이 필요하다면
with open('data.txt') as f:
for line in f:
print line
I think @movieyoda code is probably what you should use however
@movieyoda의 코드가 사용할 만하다고 생각합니다.
출처 : https://stackoverflow.com/questions/3925614/how-do-you-read-a-file-into-a-list-in-python
'개발 > 파이썬' 카테고리의 다른 글
판다스 데이터프레임에 특정 열이 있는지 확인하기 (0) | 2023.01.13 |
---|---|
Pandas 데이터프레임에서 하나의 열을 기준으로 정렬하기 (0) | 2023.01.12 |
폴더 내 모든 파일을 열 수 있는 방법 (0) | 2023.01.12 |
딕셔너리에서 key 이름을 변경하는 방법 (0) | 2023.01.11 |
판다스 데이터프레임이 비어 있는지 확인하는 방법 (0) | 2023.01.09 |