In Python I am using this file Criteria.txt and it looks like this
Homework,5,10,10
Quiz,3,20,20
Midterm,1,50,30
Final,1,100,40
I typed in this code to open and manipulate the Criteria.txt file
criteria=open('Criteria.txt','r')
criteria_line=criteria.readline()
for criteria_line in criteria:
print (criteria_line),
criteria_myline = criteria_line.strip().split(',')
print ("Assignment Type: "+criteria_myline[0])
print ("Number: "+ criteria_myline [1])
print ("Points: "+ criteria_myline [2])
print ("Weight: "+ criteria_myline [3])
print ()
The result was this
(None,)
Assignment Type: Quiz
Number: 3
Points: 20
Weight: 20
Midterm,1,50,30
(None,)
Assignment Type: Midterm
Number: 1
Points: 50
Weight: 30
Final,1,100,40
(None,)
Assignment Type: Final
Number: 1
Points: 100
Weight: 40
This was all correct except Homework didn't show up. You can see in the Criteria.txt file that Homework was the first assignment type in the list. What is wrong with this code? Why did it leave Homework out?
This happens because you read the first line of the file before your for loop starts. This causes the cursor in the file object to move to the next line, so when you iterate through for criteria_line in criteria, you're excluding the very first line (the one that includes Homework). If you remove the line
criteria_line = criteria.readline()
it should work.
This all works because a file object is an iterable and python will iterate over the lines in the file by default.
The line
criteria_line=criteria.readline()
reads the first line, the one containing Homework. In the following for loop, you immediately discard this first result.
When you criteria_line=criteria.readline(), you've already consumed one line from your file object criteria which is Homework,5,10,10, a fix is to read whenever you need the data in the for loop and as side note use with context opening file for better & safer coding:
with open('Criteria.txt') as criteria
for criteria_line in criteria:
#print (criteria_line) #for debugging
criteria_myline = criteria_line.strip().split(',')
print ("Assignment Type: "+criteria_myline[0])
print ("Number: "+ criteria_myline [1])
print ("Points: "+ criteria_myline [2])
print ("Weight: "+ criteria_myline [3])
print ()
Related
I am using Python 2.7 and this is what I am working with
print( "Massa: ", line.count("massa"))
# trying to create a new line between these two lines
print( "Lorem: ",line.count("lorem")+1)
I tried this
print( "Massa: ", line.count("massa"))\n( "Lorem: ", line.count("lorem")+1)
and did not get the results I was looking for
If you mean that you want to print it with a single print statement, this will do it.
print "Massa: ", line.count("massa"), "\n", "Lorem: ", line.count("lorem")+1
Since you are using Python 2.7 I removed the enclosing brackets, otherwise the strings are treated as elements of a tuple. I have also added a new line character \n in the middle to separate the output into 2 lines.
If you print the itmes as 2 separate print statements a new line will appear between them:
print "Massa: ", line.count("massa")
print "Lorem: ", line.count("lorem")+1
I think you can just use:
print ""
to print a newline
\n creates a line break. You can pass it as a single string and use format to place your parameters.
print("Massa: {0}\nLorem: {1}".format(line.count("massa"), line.count("lorem")+1))
I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".
Code
file = open("solutions.txt", 'r')
advice = []
read = file.readlines()
file.close()
print (read)
for i in file:
indword = i.strip()
advice.append (indword)
lst = ("screen","unresponsive","frozen","audio")
favcol = input("What is your problem? ")
probs = []
for col in lst:
if col in lst:
probs.append(col)
for line in probs:
for solution in advice:
if line in solution:
print(solution)
The text file called "solutions.txt" holds the following info:
screen: Take the phone to a repair shop where they can replace the damaged screen.
unresponsive: Try to restart the phone by holding the power button for at least 4 seconds.
frozen: Try to restart the phone by holding the power button for at least 4 seconds.
audio: If the audio or sound doesnt work, go to the nearest repair shop to fix it.
Your question reminds me a lot of my learning, so I will try give an answer to expand on your learning with lots of print statements to consider how it works carefully. It's not the most efficient or stable approach but hopefully of some use to you to move forwards.
print "LOADING RAW DATA"
solution_dictionary = {}
with open('solutions.txt', 'r') as infile:
for line in infile:
dict_key, solution = line.split(':')
print "Dictionary 'key' is: ", dict_key
print "Corresponding solution is: ", solution
solution_dictionary[dict_key] = solution.strip('\n')
print '\n'
print 'Final dictionary is:', '\n'
print solution_dictionary
print '\n'
print 'FINISHED LOADING RAW DATA'
solved = False
while not solved: # Will keep looping as long as solved == False
issue = raw_input('What is your problem? ')
solution = solution_dictionary.get(issue)
""" If we can find the 'issue' in the dictionary then 'solution' will have
some kind of value (considered 'True'), otherwise 'None' is returned which
is considered 'False'."""
if solution:
print solution
solved = True
else:
print ("Sorry, no answer found. Valid issues are 'frozen', "
"'screen' 'audio' or 'unresponsive'")
want_to_exit = raw_input('Want to exit? Y or N? ')
if want_to_exit == 'Y':
solved = True
else:
pass
Other points:
- don't use 'file' as a variable name anywhere. It's a python built-in and can cause some weird behaviour that you'll struggle to debug https://docs.python.org/2/library/functions.html
- If you get an error, don't say "crashes", you should provide some form of traceback e.g.:
a = "hello" + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-6f5e94f8cf44> in <module>()
----> 1 a = "hello" + 2
TypeError: cannot concatenate 'str' and 'int' objects
your question title will get you down-votes unless you are specific about the problem. "help me do something" is unlikely to get a positive response because the error is ambiguous, there's no sign of Googling the errors (and why the results didn't work) and it's unlikely to be of any help to anyone else in the future.
Best of luck :)
When I change the line "for i in file:" to "for i in read:" everything works well.
To output only the line starting with "screen" just forget the probs variable and change the last for statement to
for line in advice:
if line.startswith( favcol ) :
print line
break
For the startswith() function refer to https://docs.python.org/2/library/stdtypes.html#str.startswith
And: the advices of roganjosh are helpfull. Particularly the one "please don't use python keywords (e.g. file) as variable names". I spent hours of debugging with some bugs like "file = ..." or "dict = ...".
im writing some code to print a triangle with so many rows but when i try it it says,
how many rows in the triangle 5
Traceback (most recent call last):
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 6, in <module>
triangle(5)
File "U:\School\Homework\year 8\module 3\IT\python\lesson 10\extention task set by Mr Huckitns.py", line 5, in triangle
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
TypeError: 'str' object is not callable
anybodyknow whats going on here
the code i am using is
inttrow=int(input("how many rows in the triangle "))
def triangle(row):
for i in range(1,row):
x=int(inttrow)-int(i)
print((x*(str(" ")))(int(i)*(str("*")))((int(row)-int(i))*(str(" "))))
triangle(5)
The problem is the punctuation in your print statement. You're printing three strings in succession, but you forgot to put any concatenation operation between them. Try this:
print ((x*(str(" "))) + (int(i)*(str("*"))) + ((int(row)-int(i))*(str(" "))))
Further, why are you doing all these type coercions -- all of those variables already have the proper types. Cut it down to this:
print (x*" " + i*"*" + (row-i)*" ")
You are trying to contatenate strings by placing them near each other in the code like this:
("hello")(" ")("world")
Try that on the command line and see what happens. It is not the syntax of the language you are using. Then try using the plus sign.
"hello" + " " + "world"
so this piece of code is meant to take a line from a file and replace the certain line from the string with a new word/number, but it doesn't seem to work :(
else:
with open('newfile', 'r+')as myfile:
x=input("what would you like to change: \nname \ncolour \nnumber \nenter option:")
if x == "name":
print("your current name is:")
test_lines = myfile.readlines()
print(test_lines[0])
y=input("change name to:")
content = (y)
myfile.write(str.replace((test_lines[0]), str(content)))
I get the error message TypeError: replace() takes at least 2 arguments (1 given), i don't know why (content) is not accepted as an argument. This also happens for the code below
if x == "number":
print ("your current fav. number is:")
test_lines = myfile.readlines()
print(test_lines[2])
number=(int(input("times fav number by a number to get your new number \ne.g 5*2 = 10 \nnew number:")))
result = (int(test_lines[2])*(number))
print (result)
myfile.write(str.replace((test_lines[2]), str(result)))
f=open('newfile', 'r')
print("now we will print the file:")
for line in f:
print (line)
f.close
replace is a function of a 'str' object.
Sounds like you want to do something like (this is a guess not knowing your inputs)
test_lines[0].replace(test_lines[0],str(content))
I'm not sure what you're attempting to accomplish with the logic in there. looks like you want to remove that line completely and replace it?
also i'm unsure what you are trying to do with
content = (y)
the output of input is a str (which is what you want)
EDIT:
In your specific case (replacing a whole line) i would suggest just reassigning that item in the list. e.g.
test_lines[0] = content
To overwrite the file you will have to truncate it to avoid any race conditions. So once you have made your changes in memory, you should seek to the beginning, and rewrite everything.
# Your logic for replacing the line or desired changes
myfile.seek(0)
for l in test_lines:
myfile.write("%s\n" % l)
myfile.truncate()
Try this:
test_lines = myfile.readlines()
print(test_lines[0])
y = input("change name to:")
content = str(y)
myfile.write(test_lines[0].replace(test_lines[0], content))
You have no object known purely as str. The method replace() must be called on a string object. You can call it on test_lines[0] which refers to a string object.
However, you may need to change your actual program flow. However, this should circumvent the error.
You need to call it as test_lines[0].replace(test_lines[0],str(content))
Calling help(str.replace) at the interpreter.
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
Couldn't find the docs.
So I posted about another part of this code yesterday but I've run into another problem. I made a character generator for an RPG and im trying to get the program the output of a character sheet function to a .txt file, but i think whats happening is that the function may return a Nonevalue for some of the stats (which is totally normal,) and then i get an error because of that when i try to write to a .txt file. I'm totally stumped, and help would be vastly appreciated!
# Character Sheet Function.
def char_shee():
print "Name:", name
print "Class:", character_class
print "Class Powers:", class_power
print "Alignment:", alignment
print "Power:", pow, pow_mod()
print "Intelligence:", iq, iq_mod()
print "Agility:", agi, agi_mod()
print "Constitution:", con, con_mod()
print "Cynicism:", cyn, cyn_mod()
print "Charisma:", cha, cha_mod()
print "All Characters Start With 3 Hit Dice"
print"""
\t\t{0}'s History
\t\t------------------
\t\tAge:{1}
\t\t{2}
\t\t{3}
\t\t{4}
\t\t{5}
\t\t{6}
\t\t{7}
\t\t{8}
\t\t{9}
\t\tGeneral Disposition: {10}
\t\tMost important thing is: {11}
\t\tWho is to blame for worlds problems: {12}
\t\tHow to solve the worlds problems: {13}
""".format(name, age, gender_id, ethnic_pr, fcd, wg, fogo_fuck, cur_fam,fam_fuk, nat_nur, gen_dis, wha_wor, who_pro, how_pro)
char_shee()
print "Press enter to continue"
raw_input()
# Export to text file?
print """Just because I like you, let me know if you want this character
saved to a text file. Please remember if you save your character not to
name it after something important, or you might lose it.
"""
text_file = raw_input("Please type 'y' or 'n', if you want a .txt file")
if text_file == "y":
filename = raw_input("\nWhat are we calling your file, include .txt")
target = open(filename, 'w')
target.write(char_shee()
target.close
print "\nOk I created your file."
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
else:
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
EDIT: Here is the output i get:
> Please type 'y' or 'n', if you want a .txt filey
>
> What are we calling your file, include .txt123.txt <function char_shee
> at 0x2ba470> Traceback (most recent call last): File "cncg.py", line
> 595, in <module>
> target.write(pprint(char_shee)) TypeError: must be string or read-only character buffer, not None
Using print writes to sys.stdout, it doesn't return a value.
You you want char_shee to return the character sheet string to write it to a file, you'll need to just build that string instead.
To ease building the string, use a list to collect your strings:
def char_shee():
sheet = []
sheet.append("Name: " + name)
sheet.append("Class: " + character_class)
# ... more appends ...
# Return the string with newlines
return '\n'.join(sheet)
you forgot parenthesis here:
target.write(char_shee())
target.close()
and as #Martijn Pieters pointed out you should return value from char_shee(), instead of printing them.