Reading data from a txt file from string lineHow do you read from stdin?How to read a file line-by-line into a list?Find all files in a directory with extension .txt in PythonImporting files from different folderCorrect way to write line to file?How to read a large file line by lineHow to read a text file into a string variable and strip newlines?Why is reading lines from stdin much slower in C++ than Python?Pythonic way to create a long multi-line stringHow do I write JSON data to a file?
Why did Windows 95 crash the whole system but newer Windows only crashed programs?
Why would a personal invisible shield be necessary?
Why is softmax function used to calculate probabilities although we can divide each value by the sum of the vector?
Why does the Eurostar not show youth pricing?
Why did some Apollo missions carry a grenade launcher?
Why would anyone ever invest in a cash-only etf?
What is the reason for cards stating "Until end of turn, you don't lose this mana as steps and phases end"?
Why does the Rust compiler not optimize code assuming that two mutable references cannot alias?
Why did I lose on time with 3 pawns vs Knight. Shouldn't it be a draw?
Why force the nose of 737 Max down in the first place?
Did Vladimir Lenin have a cat?
Is there an antonym(a complementary antonym) for "spicy" or "hot" regarding food (I DO NOT mean "seasoned" but "hot")?
Omnidirectional LED, is it possible?
Why were contact sensors put on three of the Lunar Module's four legs? Did they ever bend and stick out sideways?
What is the German equivalent of the proverb 水清ければ魚棲まず (if the water is clear, fish won't live there)?
Piece of chess engine, which accomplishes move generation
Classic vs Modern Experience
Assuring luggage isn't lost with short layover
Filter search results by multiple filters in one operation
Why is it considered acid rain with pH <5.6?
How to have poached eggs in "sphere form"?
Wrapping IMemoryCache with SemaphoreSlim
What is more environmentally friendly? An A320 or a car?
Should I intervene when a colleague in a different department makes students run laps as part of their grade?
Reading data from a txt file from string line
How do you read from stdin?How to read a file line-by-line into a list?Find all files in a directory with extension .txt in PythonImporting files from different folderCorrect way to write line to file?How to read a large file line by lineHow to read a text file into a string variable and strip newlines?Why is reading lines from stdin much slower in C++ than Python?Pythonic way to create a long multi-line stringHow do I write JSON data to a file?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I need to write a program to read data stored in a txt file.
EX:
3147 R 1000
2168 R 6002
5984 B 2000
7086 B 8002
The first number is an "account number" the "R" is a residential classification, and the last number is "gallons used".
I need to produce a program to print this:
Account Number: 3147 Water charge: $5.0
I need to have the code read 4 lines in the text. Residential customers pay $.005 per gallon for first 6000. If higher $.007.
Business customers pay $.006 per gallon for first 8000. If higher, $.008
I need to display the product of each 4 lines.
The code below is what I tried. I may be way off.
I've tried the code below:
def main():
input_file = open('C:Python ProjectsProject
1water.txt', 'r')
empty_str = ''
line = input_file.readline()
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
while business_type == 'b' or 'B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
while business_type == 'r' or 'R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water
charge:$", water_charge)
line = input_file.readline()
input_file.close()
main()
It just runs without printing anything
python
add a comment |
I need to write a program to read data stored in a txt file.
EX:
3147 R 1000
2168 R 6002
5984 B 2000
7086 B 8002
The first number is an "account number" the "R" is a residential classification, and the last number is "gallons used".
I need to produce a program to print this:
Account Number: 3147 Water charge: $5.0
I need to have the code read 4 lines in the text. Residential customers pay $.005 per gallon for first 6000. If higher $.007.
Business customers pay $.006 per gallon for first 8000. If higher, $.008
I need to display the product of each 4 lines.
The code below is what I tried. I may be way off.
I've tried the code below:
def main():
input_file = open('C:Python ProjectsProject
1water.txt', 'r')
empty_str = ''
line = input_file.readline()
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
while business_type == 'b' or 'B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
while business_type == 'r' or 'R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water
charge:$", water_charge)
line = input_file.readline()
input_file.close()
main()
It just runs without printing anything
python
1
while business_type == 'b' or 'B'should bewhile business_type == 'b' or business_type == 'B'
– Benitok
Mar 26 at 20:39
1
In addition to the above comment, why are you checking in a while statement? I feel like you may be stuck in an infinite loop since the business type is always the same and isn't changed inside the loop/
– Joe D
Mar 26 at 20:40
add a comment |
I need to write a program to read data stored in a txt file.
EX:
3147 R 1000
2168 R 6002
5984 B 2000
7086 B 8002
The first number is an "account number" the "R" is a residential classification, and the last number is "gallons used".
I need to produce a program to print this:
Account Number: 3147 Water charge: $5.0
I need to have the code read 4 lines in the text. Residential customers pay $.005 per gallon for first 6000. If higher $.007.
Business customers pay $.006 per gallon for first 8000. If higher, $.008
I need to display the product of each 4 lines.
The code below is what I tried. I may be way off.
I've tried the code below:
def main():
input_file = open('C:Python ProjectsProject
1water.txt', 'r')
empty_str = ''
line = input_file.readline()
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
while business_type == 'b' or 'B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
while business_type == 'r' or 'R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water
charge:$", water_charge)
line = input_file.readline()
input_file.close()
main()
It just runs without printing anything
python
I need to write a program to read data stored in a txt file.
EX:
3147 R 1000
2168 R 6002
5984 B 2000
7086 B 8002
The first number is an "account number" the "R" is a residential classification, and the last number is "gallons used".
I need to produce a program to print this:
Account Number: 3147 Water charge: $5.0
I need to have the code read 4 lines in the text. Residential customers pay $.005 per gallon for first 6000. If higher $.007.
Business customers pay $.006 per gallon for first 8000. If higher, $.008
I need to display the product of each 4 lines.
The code below is what I tried. I may be way off.
I've tried the code below:
def main():
input_file = open('C:Python ProjectsProject
1water.txt', 'r')
empty_str = ''
line = input_file.readline()
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
while business_type == 'b' or 'B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
while business_type == 'r' or 'R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water
charge:$", water_charge)
line = input_file.readline()
input_file.close()
main()
It just runs without printing anything
python
python
edited Mar 26 at 20:45
Green Cloak Guy
7,1431 gold badge10 silver badges25 bronze badges
7,1431 gold badge10 silver badges25 bronze badges
asked Mar 26 at 20:34
KButlerKButler
427 bronze badges
427 bronze badges
1
while business_type == 'b' or 'B'should bewhile business_type == 'b' or business_type == 'B'
– Benitok
Mar 26 at 20:39
1
In addition to the above comment, why are you checking in a while statement? I feel like you may be stuck in an infinite loop since the business type is always the same and isn't changed inside the loop/
– Joe D
Mar 26 at 20:40
add a comment |
1
while business_type == 'b' or 'B'should bewhile business_type == 'b' or business_type == 'B'
– Benitok
Mar 26 at 20:39
1
In addition to the above comment, why are you checking in a while statement? I feel like you may be stuck in an infinite loop since the business type is always the same and isn't changed inside the loop/
– Joe D
Mar 26 at 20:40
1
1
while business_type == 'b' or 'B' should be while business_type == 'b' or business_type == 'B'– Benitok
Mar 26 at 20:39
while business_type == 'b' or 'B' should be while business_type == 'b' or business_type == 'B'– Benitok
Mar 26 at 20:39
1
1
In addition to the above comment, why are you checking in a while statement? I feel like you may be stuck in an infinite loop since the business type is always the same and isn't changed inside the loop/
– Joe D
Mar 26 at 20:40
In addition to the above comment, why are you checking in a while statement? I feel like you may be stuck in an infinite loop since the business type is always the same and isn't changed inside the loop/
– Joe D
Mar 26 at 20:40
add a comment |
2 Answers
2
active
oldest
votes
Two things. The reason nothing is appearing is because you are stuck in an infinite loop in the while loop that checks the business type. Changing that to an if statement fixes it.
In addition, when you use and, or, or some other operator, you have to specify the variable again you are comparing.
Your while statement that reads the lines of the file should look like this:
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
if business_type == 'b' or business_type =='B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
if business_type == 'r' or business_type =='R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water charge:$", water_charge)
line = input_file.readline()
Output:
('Account number:', 3147, 'Water charge:$', 5.0)
thank you. I have got it working now. I guess i wasnt too far off.
– KButler
Mar 26 at 21:12
add a comment |
The main problem is that your while loops should be simply if statements:
if business_type.lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
# So you don't get a NameError for no water_charge
water_charge = 0
The reason your while loops never terminate is two reasons: You never read the next line inside that inner loop, and a populated string like 'b' will evaluate like True:
# Strings with content act like True
if 'b':
print(True)
# True
# empty strings act as False
if not '':
print(False)
# False
The str.lower() will lowercase the string, so 'R'.lower() returns 'r'. Otherwise there is no break condition for the while and it will spin forever.
Some other suggestions:
1) When opening files, using with eliminates the need to explicitly open and close files:
with open('somefile.txt', 'r') as fh:
# Everything else goes under the with statement
2) Explicitly calling fh.readline() isn't necessary, as you can iterate over an open file directly:
with open('somefile.txt', 'r') as fh:
for line in fh:
# line is the string returned by fh.readline()
This will also terminate when fh is empty, or you reach the end of the file, you might not get explicitly '' when the file is empty, and you no longer need the while loop
3) It's generally bad practice (but also hard to maintain) magic-number code. For instance, what if the account number doesn't have exactly 5 characters? A more succinct way to do this would be with str.split(' '), which will split on spaces:
with open('somefile.txt', 'r') as fh:
for line in fh:
# This will split on spaces returning a list
# ['3147', 'R', '1000'] which can be unpacked into
# the three variables like below
account_number, business_type, gallons = line.split(' ')
# rest of your code here
In total:
# use with for clean file handling
with open('somefile.txt', 'r') as fh:
# iterate over the file directly
for line in fh:
# split and unpack
account_number, business_type, gallons = line.split(' ')
# enforce types
gallons = float(gallons)
# .strip() will remove any hanging whitespace, just a precaution
if business_type.strip().lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.strip().lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
water_charge = 0.0
print("Account number:", account_number, "Water charge:$", water_charge)
thank you for the great feedback. I went with the answer below. But i see where your code would be more efficient based on the fact that the numbers entered could be larger than 4 digits.
– KButler
Mar 26 at 21:13
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55365786%2freading-data-from-a-txt-file-from-string-line%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Two things. The reason nothing is appearing is because you are stuck in an infinite loop in the while loop that checks the business type. Changing that to an if statement fixes it.
In addition, when you use and, or, or some other operator, you have to specify the variable again you are comparing.
Your while statement that reads the lines of the file should look like this:
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
if business_type == 'b' or business_type =='B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
if business_type == 'r' or business_type =='R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water charge:$", water_charge)
line = input_file.readline()
Output:
('Account number:', 3147, 'Water charge:$', 5.0)
thank you. I have got it working now. I guess i wasnt too far off.
– KButler
Mar 26 at 21:12
add a comment |
Two things. The reason nothing is appearing is because you are stuck in an infinite loop in the while loop that checks the business type. Changing that to an if statement fixes it.
In addition, when you use and, or, or some other operator, you have to specify the variable again you are comparing.
Your while statement that reads the lines of the file should look like this:
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
if business_type == 'b' or business_type =='B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
if business_type == 'r' or business_type =='R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water charge:$", water_charge)
line = input_file.readline()
Output:
('Account number:', 3147, 'Water charge:$', 5.0)
thank you. I have got it working now. I guess i wasnt too far off.
– KButler
Mar 26 at 21:12
add a comment |
Two things. The reason nothing is appearing is because you are stuck in an infinite loop in the while loop that checks the business type. Changing that to an if statement fixes it.
In addition, when you use and, or, or some other operator, you have to specify the variable again you are comparing.
Your while statement that reads the lines of the file should look like this:
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
if business_type == 'b' or business_type =='B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
if business_type == 'r' or business_type =='R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water charge:$", water_charge)
line = input_file.readline()
Output:
('Account number:', 3147, 'Water charge:$', 5.0)
Two things. The reason nothing is appearing is because you are stuck in an infinite loop in the while loop that checks the business type. Changing that to an if statement fixes it.
In addition, when you use and, or, or some other operator, you have to specify the variable again you are comparing.
Your while statement that reads the lines of the file should look like this:
while line != empty_str:
account_number = int(line[0:4])
gallons = float(line[7:11])
business_type = line[5]
if business_type == 'b' or business_type =='B':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
if business_type == 'r' or business_type =='R':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
print("Account number:", account_number, "Water charge:$", water_charge)
line = input_file.readline()
Output:
('Account number:', 3147, 'Water charge:$', 5.0)
answered Mar 26 at 20:48
Joe DJoe D
814 bronze badges
814 bronze badges
thank you. I have got it working now. I guess i wasnt too far off.
– KButler
Mar 26 at 21:12
add a comment |
thank you. I have got it working now. I guess i wasnt too far off.
– KButler
Mar 26 at 21:12
thank you. I have got it working now. I guess i wasnt too far off.
– KButler
Mar 26 at 21:12
thank you. I have got it working now. I guess i wasnt too far off.
– KButler
Mar 26 at 21:12
add a comment |
The main problem is that your while loops should be simply if statements:
if business_type.lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
# So you don't get a NameError for no water_charge
water_charge = 0
The reason your while loops never terminate is two reasons: You never read the next line inside that inner loop, and a populated string like 'b' will evaluate like True:
# Strings with content act like True
if 'b':
print(True)
# True
# empty strings act as False
if not '':
print(False)
# False
The str.lower() will lowercase the string, so 'R'.lower() returns 'r'. Otherwise there is no break condition for the while and it will spin forever.
Some other suggestions:
1) When opening files, using with eliminates the need to explicitly open and close files:
with open('somefile.txt', 'r') as fh:
# Everything else goes under the with statement
2) Explicitly calling fh.readline() isn't necessary, as you can iterate over an open file directly:
with open('somefile.txt', 'r') as fh:
for line in fh:
# line is the string returned by fh.readline()
This will also terminate when fh is empty, or you reach the end of the file, you might not get explicitly '' when the file is empty, and you no longer need the while loop
3) It's generally bad practice (but also hard to maintain) magic-number code. For instance, what if the account number doesn't have exactly 5 characters? A more succinct way to do this would be with str.split(' '), which will split on spaces:
with open('somefile.txt', 'r') as fh:
for line in fh:
# This will split on spaces returning a list
# ['3147', 'R', '1000'] which can be unpacked into
# the three variables like below
account_number, business_type, gallons = line.split(' ')
# rest of your code here
In total:
# use with for clean file handling
with open('somefile.txt', 'r') as fh:
# iterate over the file directly
for line in fh:
# split and unpack
account_number, business_type, gallons = line.split(' ')
# enforce types
gallons = float(gallons)
# .strip() will remove any hanging whitespace, just a precaution
if business_type.strip().lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.strip().lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
water_charge = 0.0
print("Account number:", account_number, "Water charge:$", water_charge)
thank you for the great feedback. I went with the answer below. But i see where your code would be more efficient based on the fact that the numbers entered could be larger than 4 digits.
– KButler
Mar 26 at 21:13
add a comment |
The main problem is that your while loops should be simply if statements:
if business_type.lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
# So you don't get a NameError for no water_charge
water_charge = 0
The reason your while loops never terminate is two reasons: You never read the next line inside that inner loop, and a populated string like 'b' will evaluate like True:
# Strings with content act like True
if 'b':
print(True)
# True
# empty strings act as False
if not '':
print(False)
# False
The str.lower() will lowercase the string, so 'R'.lower() returns 'r'. Otherwise there is no break condition for the while and it will spin forever.
Some other suggestions:
1) When opening files, using with eliminates the need to explicitly open and close files:
with open('somefile.txt', 'r') as fh:
# Everything else goes under the with statement
2) Explicitly calling fh.readline() isn't necessary, as you can iterate over an open file directly:
with open('somefile.txt', 'r') as fh:
for line in fh:
# line is the string returned by fh.readline()
This will also terminate when fh is empty, or you reach the end of the file, you might not get explicitly '' when the file is empty, and you no longer need the while loop
3) It's generally bad practice (but also hard to maintain) magic-number code. For instance, what if the account number doesn't have exactly 5 characters? A more succinct way to do this would be with str.split(' '), which will split on spaces:
with open('somefile.txt', 'r') as fh:
for line in fh:
# This will split on spaces returning a list
# ['3147', 'R', '1000'] which can be unpacked into
# the three variables like below
account_number, business_type, gallons = line.split(' ')
# rest of your code here
In total:
# use with for clean file handling
with open('somefile.txt', 'r') as fh:
# iterate over the file directly
for line in fh:
# split and unpack
account_number, business_type, gallons = line.split(' ')
# enforce types
gallons = float(gallons)
# .strip() will remove any hanging whitespace, just a precaution
if business_type.strip().lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.strip().lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
water_charge = 0.0
print("Account number:", account_number, "Water charge:$", water_charge)
thank you for the great feedback. I went with the answer below. But i see where your code would be more efficient based on the fact that the numbers entered could be larger than 4 digits.
– KButler
Mar 26 at 21:13
add a comment |
The main problem is that your while loops should be simply if statements:
if business_type.lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
# So you don't get a NameError for no water_charge
water_charge = 0
The reason your while loops never terminate is two reasons: You never read the next line inside that inner loop, and a populated string like 'b' will evaluate like True:
# Strings with content act like True
if 'b':
print(True)
# True
# empty strings act as False
if not '':
print(False)
# False
The str.lower() will lowercase the string, so 'R'.lower() returns 'r'. Otherwise there is no break condition for the while and it will spin forever.
Some other suggestions:
1) When opening files, using with eliminates the need to explicitly open and close files:
with open('somefile.txt', 'r') as fh:
# Everything else goes under the with statement
2) Explicitly calling fh.readline() isn't necessary, as you can iterate over an open file directly:
with open('somefile.txt', 'r') as fh:
for line in fh:
# line is the string returned by fh.readline()
This will also terminate when fh is empty, or you reach the end of the file, you might not get explicitly '' when the file is empty, and you no longer need the while loop
3) It's generally bad practice (but also hard to maintain) magic-number code. For instance, what if the account number doesn't have exactly 5 characters? A more succinct way to do this would be with str.split(' '), which will split on spaces:
with open('somefile.txt', 'r') as fh:
for line in fh:
# This will split on spaces returning a list
# ['3147', 'R', '1000'] which can be unpacked into
# the three variables like below
account_number, business_type, gallons = line.split(' ')
# rest of your code here
In total:
# use with for clean file handling
with open('somefile.txt', 'r') as fh:
# iterate over the file directly
for line in fh:
# split and unpack
account_number, business_type, gallons = line.split(' ')
# enforce types
gallons = float(gallons)
# .strip() will remove any hanging whitespace, just a precaution
if business_type.strip().lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.strip().lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
water_charge = 0.0
print("Account number:", account_number, "Water charge:$", water_charge)
The main problem is that your while loops should be simply if statements:
if business_type.lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
# So you don't get a NameError for no water_charge
water_charge = 0
The reason your while loops never terminate is two reasons: You never read the next line inside that inner loop, and a populated string like 'b' will evaluate like True:
# Strings with content act like True
if 'b':
print(True)
# True
# empty strings act as False
if not '':
print(False)
# False
The str.lower() will lowercase the string, so 'R'.lower() returns 'r'. Otherwise there is no break condition for the while and it will spin forever.
Some other suggestions:
1) When opening files, using with eliminates the need to explicitly open and close files:
with open('somefile.txt', 'r') as fh:
# Everything else goes under the with statement
2) Explicitly calling fh.readline() isn't necessary, as you can iterate over an open file directly:
with open('somefile.txt', 'r') as fh:
for line in fh:
# line is the string returned by fh.readline()
This will also terminate when fh is empty, or you reach the end of the file, you might not get explicitly '' when the file is empty, and you no longer need the while loop
3) It's generally bad practice (but also hard to maintain) magic-number code. For instance, what if the account number doesn't have exactly 5 characters? A more succinct way to do this would be with str.split(' '), which will split on spaces:
with open('somefile.txt', 'r') as fh:
for line in fh:
# This will split on spaces returning a list
# ['3147', 'R', '1000'] which can be unpacked into
# the three variables like below
account_number, business_type, gallons = line.split(' ')
# rest of your code here
In total:
# use with for clean file handling
with open('somefile.txt', 'r') as fh:
# iterate over the file directly
for line in fh:
# split and unpack
account_number, business_type, gallons = line.split(' ')
# enforce types
gallons = float(gallons)
# .strip() will remove any hanging whitespace, just a precaution
if business_type.strip().lower() == 'b':
if gallons > 8000:
water_charge = gallons * .008
else:
water_charge = gallons * .006
elif business_type.strip().lower() == 'r':
if gallons > 6000:
water_charge = gallons * .007
else:
water_charge = gallons * .005
else:
water_charge = 0.0
print("Account number:", account_number, "Water charge:$", water_charge)
edited Mar 26 at 21:02
answered Mar 26 at 20:49
C.NivsC.Nivs
5,1191 gold badge6 silver badges22 bronze badges
5,1191 gold badge6 silver badges22 bronze badges
thank you for the great feedback. I went with the answer below. But i see where your code would be more efficient based on the fact that the numbers entered could be larger than 4 digits.
– KButler
Mar 26 at 21:13
add a comment |
thank you for the great feedback. I went with the answer below. But i see where your code would be more efficient based on the fact that the numbers entered could be larger than 4 digits.
– KButler
Mar 26 at 21:13
thank you for the great feedback. I went with the answer below. But i see where your code would be more efficient based on the fact that the numbers entered could be larger than 4 digits.
– KButler
Mar 26 at 21:13
thank you for the great feedback. I went with the answer below. But i see where your code would be more efficient based on the fact that the numbers entered could be larger than 4 digits.
– KButler
Mar 26 at 21:13
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55365786%2freading-data-from-a-txt-file-from-string-line%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
while business_type == 'b' or 'B'should bewhile business_type == 'b' or business_type == 'B'– Benitok
Mar 26 at 20:39
1
In addition to the above comment, why are you checking in a while statement? I feel like you may be stuck in an infinite loop since the business type is always the same and isn't changed inside the loop/
– Joe D
Mar 26 at 20:40