csv, txt, py 파일을 사용하여 다양한 솔루션을 살펴 보았지만 원하는 것을 얻을 수 없었습니다.
나는 다음 코드를 시도 해왔다.
print('Enter the result of your last reading=')
newReading = input()
reading = [int(newReading)]
with open('avg.py', 'a') as f:
f.write('reading = ' . reading)
from avg.py import reading as my_list
print(my_list)
해결책
filename = "avg.txt"
while True:
new_reading = input("\nEnter the result of your last reading: ")
with open(filename, 'a') as f_obj:
f_obj.write(new_reading)
with open(filename) as f_obj:
contents = f_obj.read()
reading = list(contents)
print(reading)
산출
(xenial)vash@localhost:~/python$ python3 read_write_files.py Enter the result of your last reading: 1 ['1'] Enter the result of your last reading: 2 ['1', '2'] Enter the result of your last reading: 3 ['1', '2', '3']
코멘트
이 경로는 두 번째 코드를 사용하여 파일을 연 다음 데이터를 읽고 contents
. 그런 다음을 사용하여 내용을 목록으로 바꿀 수 있습니다 list(contents)
.
여기에서 목록을 reading
인쇄하는 것 외에 다른 작업을 할 수 있습니다 . 또한 이것을 if
else
루프 로 바꾸고 q to quit
프로그램을 끝내기 위해 etc 와 같은 조건을 만드는 것에 대해 생각할 것 입니다.
이 같은:
filename = "avg.txt"
while True:
new_reading = input("\nEnter the result of your last reading" \
"('q' to quit): ")
if new_reading == "q":
break
else:
with open(filename, 'a') as f_obj:
f_obj.write(new_reading)
with open(filename) as f_obj:
contents = f_obj.read()
reading = list(contents)
print(reading)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다