I am writing a program that will open a specified file then "wrap" all lines that are longer than a given line length and print the result on the screen.
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r+')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
wr = textwrap.TextWrapper()
wr.width = lLength
wr.expand_tabs = True
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
print(wraped)
main()
When I do this instead of wrapping it prints everything in the file as a list with commas and brackets, instead of wrapping them.
textwrap.TextWrapper.wrap "returns a list of output lines, without final newlines."
You could either join them together with a linebreak
print('\n'.join(wrapped))
or iterate through and print them one at a time
for line in wrapped:
print(line)
Related
This is the code to search a particular entry in a file:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
num = "0"
flag = False
while (num != ""):
num = test_file.readline()
if (num == num2find):
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The test file is:
1
2
3
4
5
If I input 2, the code still outputs "Number not found."
Every time you read a line from a text file, you are getting "\n" at the end of the string line, so the problem you are facing is that you are comparing "2" to "2\n" which is not the same.
You could take advantage of with to pen your file. This way you do not need to worry about closing the file once you are done with it. Also, you do not need to pass the "r" argument since it is the default mode for open.
You should use a for loop instead of that needless while loop. The for loop will terminate automatically when all the lines in the file have been read.
One more improvement you could make is to rename the flag flag to found, and to print the result once the file has been processed.
num2find = int(input("Enter a number to find: "))
found = False # rename flag
with open("testfile.txt") as test_file: # use with to avoid missing closing the file
for line in test_file: # use a for loop to iterate over each line in the file
num = int(line)
if num == num2find:
found = True
break
if found: # print results at the end once file was processed
print("Number found.")
else:
print("Number not found.")
Each line in the test file contains two characters - the number and a newline. Since "2" does not equal "2\n", your number is not being found. To fix this, use the int function to parse your lines, since it ignores whitespace (like the \n) character:
num2find = int(input("Enter a number to find: "))
flag = False
with open("testfile.txt", "r") as test_file:
for line in test_file:
num = int(line)
if num == num2find:
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The easiest and the most logical solution I could come up with after all the feedback was this:
num2find = int(input("Enter a number to find: "))
file_data = open("testfile.txt", "r")
found = False
for data in file_data:
if int(data) == num2find:
found = True
if found:
print("\nNumber found.")
else:
print("\nNumber not found.")
file_data.close()
You need to add .rstrip() on num = test_file.readline()
Try something like this:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
file_data = test_file.readlines()
flag = False
for item in file_data:
if num2find == item.rstrip():
flag = True
break
if not flag:
print("\nNumber not found.")
else:
print("Number found")
Don't use .readline() like that, use readlines() instead
I have been working on this code for a couple of hours now, and I am rather unsure what the problem is.
import random#imports random
import os#Imports os
print("Welcome to the maths quiz") # Welcomes user to quiz
score = (0)
def details():
plr_name = input ("Please Input Name:") # Asks user for name
plr_class = input("Input class number: ") # Asks the user for class numer
return (plr_name, plr_class)
def Q():
while qno < 10: # loops while qno is under 10
ran_num1 = random.randint(1,99) # Generates the first random number
ran_num2 = random.randint(1,99) # Generates the second random number
ran_fun = random.choice("X-+") # Picks a random function
print(ran_num1,ran_fun,ran_num2,"=") # Prints the Sum for the user
if ran_fun == "X":
sum_ans = ran_num1 * ran_num2 # Does the sum if it is a multiplication
if ran_fun == "+":
sum_ans = ran_num1 + ran_num2 # Does the sum if it is a addition
if ran_fun == "-":
sum_ans = ran_num1 - ran_num2 # Does the sum if it is a subtraction
plr_ans = int(input()) # Gets the user's answer
if plr_ans == sum_ans:
print("Correct!") # Prints correct
score = score + 1 # Adds 1 to score
else:
print("Incorrect!")
qno = qno + 1 # Adds 1 to qno
def plr_list_make(lines, listoreder):
index = 0
plr_names =[]
plr_scores =[]
for line in lines:
if listorder == 1:
column =0
rev = False
else:
column = 1
rev = True
return sorted(zip(plr_names, plr_scores),key = lambda x:(x[column]),reverse = rev)
def fileUP(plr_name, score, line ):
found = False
index = 0
for line in lines:
if line.startswith(plr_name):
line = line.strip("\n") + ","+str(score+"\n")
lines[index] = line
found = True
index = index + 1
if not found:
lines.append(plr_name+"|" +str(score)+"\n")
return lines
def save (plr_name, plr_class, score):
filename = "QuizScore_"+plr_class+".txt"
try:
fileI = open(filename)
except IOError:
fileI = open(filename, "w+")
fileI = open(filename)
lines = fileI.readlines()
fileI.close
lines = FileUP(plr_name, score, lines)
fileO = open(filename, "w")
fileO.writelines(lines)
fileO.close
def disp_list(): ## intialise_list
student_list=[]
filename = "QuizScore_"+plr_class+".txt"
try:
## open file read into list "lines"
input_file = open(filename)
lines = input_file.readlines() ## read file into list "lines"
input_file.close
student_list = create_student_list(lines, listorder) ### update "lines" with student list as requested by user
## output sorted list
for counter in range(len(student_list)):
print ("Name and Score: ", student_list[counter][0], student_list[counter][1])
except IOError:
print ("no class file!!!")
def menu():
print ("1 Test")
print ("2 Alphabetical")
print ("3 Highscore")
print ("4 Avg Score")
def Run():
selection = 0
while selection != 5:
menu()
option = int(input("Please select option: "))
if option == 1:
name, plr_class = details()
save(name, plr_class, Q())
else:
plr_class = input("input class ")
disp_list(plr_class, option-1)
Run()
Errors:
Traceback (most recent call last):
File "C:\Users\user\Documents\CharlieStockham\cgsca\ca2.py", line 117, in
Run()
File "C:\Users\user\Documents\CharlieStockham\cgsca\ca2.py", line 113, in Run
save(name, plr_class, Q())
File "C:\Users\user\Documents\CharlieStockham\cgsca\ca2.py", line 74, in save
lines = FileUP(plr_name, score, lines)
NameError: global name 'FileUP' is not defined
Line 110:
name, plr_class = details()
But the details function does not return anything - so Python tries to assign the default return value None to the tuple name, plr_class. It can't do this, because None is not an iterable (you can't assign two things to it). To fix it, add the following line to your details function:
return (plr_name, plr_class)
(I haven't tested this.)
I like your game but it's buggy as a mofo :P
score and qno aren't properly defined. Define them in the functions that need them, define them globally or pass them to the relevant functions as arguments.
details() doesn't return anything but you still attempt to use its output to define two other variables. Add return (plr_name, plr_class) to details()
Every time you cast user input to int without checking its value, your program will crash if an int can't be cast. This applies here:
option = int(input("Please select option: "))
here
plr_ans = int(input())#Gets the user's answer
and elsewhere.
Since your program is input-heavy you could make a a function to which you pass the expected datatype and an optional string to display to the user. This way you wouldn't have to write try/except 10 times and your program wouldn't crash on unexpected input.
In def fileUP(plr_name, score, line ): you have for line in lines: but lines isn't defined. Thus, the save() function that calls FileUP() also fails. Also, FileUP and fileUP are not the same thing. You call the function with a capital "f" but the defintion of the function calls it fileUP with a lower case "f".
While we're at it, the file handling in def save (plr_name, plr_class, score):looks weird. The standard way of opening files for simple reading and writing in Python is via with open().
disp_list() should take one or two arguments but it doesn't at the moment so this error is raised:
TypeError: disp_list() takes 0 positional arguments but 2 were given
These 2 positional arguments were given here:
disp_list(plr_class, option-1)
I am trying to create two programs one that writes the data to file golf.txt and the second which reads the records from golf.txt and displays them. The first program I am trying to get the program to quit when you leave the input field blank. Here's my code for the first program.
#Program that reads each player's name and golf score as input
#Save to golf.txt
outfile = open('golf.txt', 'w')
#Enter input, leave blank to quit program
while True:
name = input("Player's name(leave blank to quit):")
score = input("Player's score(leave blank to quit):")
if input ==" ":
break
#write to file golf.txt
outfile.write(name + "\n")
outfile.write(str(score) + "\n")
outfile.close()
With the second program I can't get the program to display the output I want on one line. Here's the second program.
#Golf Scores
# main module/function
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
# reads the player array from the file
player = infile.read()
# reads the score array from the file
score = infile.read()
# prints the names and scores
print(player + "scored a" + score)
# closes the file
infile.close()
# calls main function
main()
Any help or suggestions I can get would be greatly appreciated.
Two main problems:
1.) you first code has if input == ' ' which is wrong in two ways:
input is a function. you already saved the input so you should be comparing with name and score.
input returns a '' when you dont input anything, not a ' '.
so change to: if name == '' or score == '': or even if '' in (name,score): (does the same things)
2.) file.read() will automatically read EVERYTHING in the file as one string. You want to split it into each component so you can either do something like:
player,score = file.readlines()[:2]
or
player = file.readline()
score = file.readline()
then print (with leading and trailing spaces in your middle string!)
print(player + " scored a " + score)
Got both programs working
program 1:
#Program that reads each player's name and golf score as input
#Save to golf.txt
outfile = open('golf.txt', 'w')
#Enter input, leave blank to quit program
while True:
name = input("Player's name(leave blank to quit):")
if name == "":
break
score = input("Player's score:")
#write to file golf.txt
outfile.write(name + "\n")
outfile.write(str(score) + "\n")
outfile.close()
program 2:
#Golf Scores
# main module/function
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
# reads the player array from the file
name = infile.readline()
while name != '':
# reads the score array from the file
score = infile.readline()
# strip newline from field
name = name.rstrip('\n')
score = score.rstrip('\n')
# prints the names and scores
print(name + " scored a " + score)
# read the name field of next record
name = infile.readline()
# closes the file
infile.close()
# calls main function
main()
Eliminate spaces from the input before checking (I would use .strip() method). And compare it to the empty string "" instead of space(s) " ".
With the "while true" block you keep asking and taking the names and the scores, but you overwrite them so you always will have just the last pair.
You need to keep them all, so you can make a list:
names_and_scores = []
while True:
name = input("Player's name(leave blank to quit):").strip()
if name == "":
break
score = input("Player's score:").strip()
if name != "" and score != "":
names_and_scores.append("{}; {}".format(name, score))
with open('golf.txt', 'w') as outfile:
outfile.write("\n".join(names_and_scores))
The second program opens the file, read lines one by one, splits them and print:
with open('golf.txt', 'r') as infile:
for line in infile:
name, score = line.strip().split("; ")
print("{} scored a {}.".format(name, score))
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
f = open(fileName,'r')
numbers = []
for line in f:
sentenceInLine = line.split('\n')
for word in sentenceInLine:
if word != '':
numbers.append(word)
print numbers
print len(numbers)
print numbers[n-1]
if n == 0:
print "There is no 0 line"
break
i think you missed to split sentenceInLine like sentenceInLine.split(' ')
You are looping over each line, then you split lines based on '\n'. That \n is a line break character. That would confuse your logic right there.
So it is a bit confusing what you are trying to do but you should check n after the user has inputed a value for n. not at the end.
You may want to also catch the exception where file cannot be found I think this is what you need:
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
if n == 0:
print "There is no 0 line"
sys.exit();
try:
f = open(fileName,'r')
except IOError:
print "Could not find file"
sys.exit()
First off thank you for your time and answers. My task is to have my program open a text file, read its data so every word is a different string, and creating a HTML document displaying each one of these strings into a random color. So pretty much it wants us to take every word from a text file change each word into a random color and create a HTML document out of it. This is the code i have so far:
import random
def main():
filename = input("Enter Text File:")
infile = open(filename, "r")
filename2 = input("Enter HTML Document:")
outfile = open(filename2, "w")
print("<html>", file=outfile)
print(" <head>", file=outfile)
print(" </head>", file=outfile)
print(" <body>", file=outfile)
filestring = infile.read()
file = filestring.split()
filelength = len(file)
num = int(random.uniform(0,256))
num1 = int(random.uniform(0,256))
num2 = int(random.uniform(0,256))
i = 0
for i in range(filelength):
r = num
g = num1
b = num2
rgb = "{0:02X}{1:02X}{2:02X}".format(r, g, b)
print(' <span style="color:#{0}">{1}</span>'.format(rgb, file[i]),file=outfile)
i = 0 + 1
print(" </body>", file=outfile)
print("</html>", file=outfile)
main()
This code works but it does not change each individual word into a random color it just changes all the words into the same color. I appreciate the answers.
Since this is homework, I'll limit my answer to a hint:
You're currently generating one random colour, and applying it to every word. What you should be doing is generating a new random colour for every word.
this code should be in the loop (for i in range(filelength):)
num = int(random.uniform(0,256))
num1 = int(random.uniform(0,256))
num2 = int(random.uniform(0,256))
Your code (I haven't executed it) seems to be correct(ignoring the absence of Exception Handling). You need to change num, num1 and num2 for each word. That would mean, you need to put num, num1 and num2 inside the loop for i in range(filelength):.
Try this:
import random
def main():
filename = input("Enter Text File:").strip()
infile = open(filename, "r")
filename2 = input("Enter HTML Document:").strip()
outfile = open(filename2, "w")
print("<html><head></head><body>",file=outfile)
for line in infile:
for word in line.split():
(r,g,b)=[int(random.uniform(0,256)) for x in range(3)]
rgb = "{0:02X}{1:02X}{2:02X}".format(r, g, b)
print(' <span style="color:#{0}">{1} </span>'.format(rgb,word),file=outfile)
print("<br>",file=outfile)
print(" </body>", file=outfile)
print("</html>", file=outfile)
main()