2016-08-25 2 views
0

현재 목록의 번호에 텍스트 파일의 번호를 곱하려고 시도하지만 오류가 발생합니다. = Can't multiply sequence by non-int of type 'NonType',목록의 번호와 텍스트 파일의 번호를 곱합니까?

더 좋은 방법이 있습니까?

text_file =open("read_it.txt", "r") 
pricetxt=print(text_file.readlines()[2]) 
price1 = pricetxt*(items2[1]) 
print(price1) 

답변

1

print() 반환 없음 당신이 pricetxt()에 보존되어있다. 또한 문자열 인 결과를 int (올바른 데이터 인 경우)으로 변환해야합니다. 또한 파일을 열기 위해 with 문을 사용하는 것이 더 좋습니다. 블록의 끝에서 자동으로 파일을 닫을 것이기 때문입니다.

with open("read_it.txt") as text_file: 
    try: 
     price = int(text_file.readlines()[2]) 
    except ValueError: 
     # do something else 
    else: 
     new_price = price * items2[1] 

또한 items2[1]은 정수 여야합니다. 그렇지 않다면 pricetxt 다음에 try 블록에서 수행 할 수있는 정수로 변환해야합니다.

+0

일단 변수가'int'로 변환되면 변수 이름은'pricetxt'보다는'priceval'이나'price'이어야합니다. –

+0

@StevenRumbalski 좋은 지적! – Kasramvd

+0

고마워요. 목록에있는 숫자가 정수 또는 문자열로 기록되어 있습니까? –

관련 문제