问题描述:
I am writing a program where it needs to store some numbers.
2000
0
1100
1400
75
100
But when reading it removes zeros from some of numbers and doing other mystical things.
with open('stats.txt') as f:
money = f.readline(1)
quantity = f.readline(2)
min_earnings = f.readline(3)
max_earnings = f.readline(4)
min_current_cost = f.readline(5)
max_current_cost = f.readline(6)
print(money, quantity, min_earnings, max_earnings, min_current_cost, max_current_cost)
And he brings out:2 0 0 0 1100 1400
I tried to use int(), google about this problem but I find nothing.
What should I do to fix this?
解决方案 1:[1]
The number you pass to readline
is the number of bytes to read. You don’t need to say which line (number) you want to read, reading a file (almost always) starts at the beginning and once a line is read, the next line is up for reading.
Just remove the numbers from your readline
s and the code reads and prints whole lines.
解决方案 2:[2]
Wouldnt it just be easier to put each line into a list and then print the list?
lines = []
with open('stats.txt') as f:
lines.append(f.readline())
print(*lines, sep = ", ")
解决方案 3:[3]
You’re on the right track, but your f.readline(n) isn’t quite doing what you think it is. There’re a lot of solutions to this (I would use a 2D dictionary if you plan on storing multiple “bank accounts”), but this is a simple approach that might lead you to see one of many solutions.
status = []
with open('stats.txt') as f:
for i in f:
status.append(i.strip())
money = status[0]
quantity = status[1]
min_earnings = status[2]
max_earnings = status[3]
min_current_cost = status[4]
max_current_cost = status[5]
By no means is it optimal, or elegant, but I hope you can see what i
is more clearly this way when we loop through readline()
. Let me know if there is any confusion.
参考链接:
Copyright Notice: This article follows StackOverflow’s copyright notice requirements and is licensed under CC BY-SA 3.0.
Article Source: StackOverflow
[1] Robert
[3] nulzo