Hello everyone i have an issue with this problem, the problem is i need to reset the count after every line in the file, i put a comment so you can see where i want to reset the count.
The program is suppose to cut each line after every specified lineLength.
def insert_newlines(string, afterEvery_char):
lines = []
for i in range(0, len(string), afterEvery_char):
lines.append(string[i:i+afterEvery_char])
string[:afterEvery_char] #i want to reset here to the beginning of every line to start count over
print('\n'.join(lines))
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r')
file = openFile.read()
lineLength = int(input("enter a number between 10 & 20: "))
while (lineLength < 10) or (lineLength > 20) :
print("Invalid input, please try again...")
lineLength = int(input("enter a number between 10 & 20: "))
print("\nYour file contains the following text: \n" + file + "\n\n") # Prints original File to screen
print("Here is your output formated to a max of", lineLength, "characters per line: ")
insert_newlines(file, lineLength)
main()
Ex. If a file has 3 lines like this with each line having 20 chars
andhsytghfydhtbcndhg
andhsytghfydhtbcndhg
andhsytghfydhtbcndhg
after the lines are cut it should look like this
andhsytghfydhtb
cndhg
andhsytghfydhtb
cndhg
andhsytghfydhtb
cndhg
i want to RESET the count after every line in the file.
I'm not sure I understand your problem, but from your comments it appears you simply want to cut the input string (file) to lines lineLength long. That is already done in your insert_newlines(), no need for the line with comment there.
However, if you want to output lines meaning strings ending with newline char that should be no more than lineLength long, then you could simply read the file like this:
lines = []
while True:
line = openFile.readline(lineLength)
if not line:
break
if line[-1] != '\n':
line += '\n'
lines.append(line)
print(''.join(lines))
or alternatively:
lines = []
while True:
line = openFile.readline(lineLength)
if not line:
break
lines.append(line.rstrip('\n'))
print('\n'.join(lines))
I don't understand the issue here, the code seems to work just fine:
def insert_newlines(string, afterEvery_char):
lines = []
# if len(string) is 100 and afterEvery_char is 10
# then i will be equal to 0, 10, 20, ... 90
# in lines we'll have [string[0:10], ..., string[90:100]] (ie the entire string)
for i in range(0, len(string), afterEvery_char):
lines.append(string[i:i+afterEvery_char])
# resetting i here won't have any effect whatsoever
print('\n'.join(lines))
>>> insert_newlines('Beautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\n..', 10)
Beautiful
is better
than ugly.
Explicit
is better
than impli
cit.
Simpl
e is bette
r than com
plex.
..
isn't that what you want?
Related
I am trying to achieve:
User input word, and it outputs how many lines contain that word also sees it up to the first ten such lines. If no lines has the words, then your program must output Not found.
My code so far:
sentences = []
with open("txt.txt") as file:
for line in file:
words = line.split()
words_count += len(words)
if len(words) > len(maxlines.split()):
maxlines = line
sentences.append(line)
word = input("Enter word: ")
count = 0
for line in sentences:
if word in line:
print(line)
count += 1
print(count, "lines contain", word)
if count == 0:
print("Not found.")
How would I only print first 10 line regardless the amount of lines
Thank you!
If you want to iterate 10 times (old style, not pythonic at all)
index = 0
for line in file:
if index >= 10:
break
# do stuff 10 times
index += 1
Without using break, just put the stuff inside the condition. Notice that the loop will continue iterating, so this is not really a smart solution.
index = 0
for line in file:
if index < 10:
# do stuff 10 times
index += 1
However this is not pythonic at all. the way you should do it in python is using range.
for _ in range(10):
# do stuff 10 times
_ means you don't care about the index and just want to repeat 10 times.
If you want to iterate over file and keeping the index (line number) you can use enumerate
for lineNumber, line in enumerate(file):
if lineNumber >= 10:
break
# do stuff 10 times
Finally as#jrd1 suggested, you can actually read all the file and then only slice the part that you want, in your case
sentences[:10] # will give you the 10 first sentences (lines)
just change your code like this, it should help:
for line in sentences:
if word in line:
if count < 10: print(line) # <--------
count += 1
I have this:
from random_word import RandomWords
import time
h = open('/home/rodrigo/Documents/num.txt', 'r')
content = h.readline()
print (content)
a = 0
for line in content:
for i in line:
if i.isdigit() == True:
a += int(i)
r = RandomWords()
key = r.get_random_words()
time.sleep(3)
keys = key[:a]
time.sleep(1)
for key in keys:
print(key)
I'm trying to read and use the number on the first line of a .txt file.
In the .txt file I have just typed the number:
50
However, this code reads only the first digit of the number fifty and the result is that the function print(key) prints only 5 words (it should print 50 words).
If I change the .txt file to the number: 55
The print(key) prints 10 words and not 55 words.
(the function is adding the digits/numeric units of the .txt file)
Can anybody help? How to print an amount of words exactly equal to the number typed in the .txt file?
It reads both digits. But it reads it to a string "50". You then iterate over the digits, convert them to ints and add them up, i.e. int("5") + int("0"). Which gives you 5 (obviously).
So just replace your whole loop with
a = int(content)
if you want to check that file only has digits:
try:
a = int(content)
except ValueError:
print("The content is not intiger")
content is a string, you are iterating through characters in the string in your first for loop (and iterating over the single character string line once with your nested for loop).
If you only need the one line, replacing your first for loop with this should work:
if content.isdigit() == True:
a += int(content)
if you need multiple lines and to add them seperately, add each line to a list like this:
from random_word import RandomWords
import time
h = open('/home/rodrigo/Documents/num.txt', 'r')
content = []
line = h.readline()
while line:
content.append(line)
line = h.readline()
print (content)
a = 0
for line in content: # You only need one for loop.
if line.isdigit() == True:
a += int(i)
r = RandomWords()
key = r.get_random_words()
time.sleep(3)
keys = key[:a]
time.sleep(1)
for key in keys:
print(key)
Hello, I am fairly new to python and wondering how to convert this while loop to a for loop. I am not sure how to keep looping the inputs so it keeps asking Enter a line until GO and then say Next until STOP then display the count of lines.
def keyboard():
"""Repeatedly reads lines from standard input until a line is read that
begins with the 2 characters "GO". Then a prompt Next: , until a line is
read that begins with the 4 characters "STOP". The program then prints a
count of the number of lines between the GO line and the STOP line (but
not including them in the count) and exits."""
line = input("Enter a line: ")
flag = False
count = 0
while(line[:4] != "STOP"):
if (line[:2] == "GO"):
flag = True
if flag:
line = input("Next: ")
count += 1
else:
line = input("Enter a line: ")
print(f"Counted {count-1} lines")
keyboard()
With these inputs:
ignore me
and me
GO GO GO!
I'm an important line
So am I
Me too!
STOP now please
I shouldn't even be read let alone printed
Nor me
Should display/result in:
Enter a line: ignore me
Enter a line: and me
Enter a line: GO GO GO!
Next: I'm an important line
Next: So am I
Next: Me too!
Next: STOP now please
Counted 3 lines
You just need an infinity for loop which is what while True essentially is.
This answer has it: Infinite for loops possible in Python?
#int will never get to 1
for _ in iter(int, 1):
pass
So just replace your while loop with the above and add a break condition.
def keyboard():
"""Repeatedly reads lines from standard input until a line is read that
begins with the 2 characters "GO". Then a prompt Next: , until a line is
read that begins with the 4 characters "STOP". The program then prints a
count of the number of lines between the GO line and the STOP line (but
not including them in the count) and exits."""
line = input("Enter a line: ")
flag = False
count = 0
for _ in iter(int, 1):
if line[:4] == "STOP":
break
if (line[:2] == "GO"):
flag = True
if flag:
line = input("Next: ")
count += 1
else:
line = input("Enter a line: ")
print(f"Counted {count-1} lines")
keyboard()
I've been getting stuck in the total_num() function as it gives the error
"ValueError: invalid literal for int() with base 10: ''"
I know how to do it if its a defined list but if its set by the user I get confused.
def total_num():
total = 0
num_file = open("num_list.txt", "r")
line = num_file.read()
while line != "":
num1 = int(num_file.readline())
total = total + num1
print total
def read_num():
num_file = open("num_list.txt", "r")
for line in num_file:
print line.rstrip("\n")
def write_num():
num = input("Enter a number: ")
num_file = open("num_list.txt", "w")
num_consec = 0
for x in range(num):
num_consec = num_consec + 1
num_file.write(str(num_consec)+ "\n")
num_file.close()
def main():
write_num()
read_num()
total_num()
main()
The error is because you are getting an empty string from your text file. Look at this bit of code; you are reading the whole file into memory.
line = num_file.read()
while line != "":
Over here, unless you opened an empty file line != "" you are comparing the whole file with an empty string. So you will keep on looping until your num1 = int(num_file.readline()) reads an empty line from the file.
You can find the solution if you look at your read_num method.
for line in num_file:
try:
total += int(line)
except ValueError:
print "Invalid data in ", line
By using try except you are able to handle the situation where the file might contain other invalid texts.
You are reading the file in an odd way - namely, twice. read() puts the entire file contents into a string. If you repeatedly check whether there are characters in it, and then never change it, it will either not execute or loop infinitely.
Using input() to get a number will work, but it's better to use raw_input() and cast with int() for safety. Also, xrange() is a better practice than range() in Python 2. You don't need to keep a manual counter if you're already iterating over range(), either.
Overall, your code could be condensed to this:
def write_num():
num = int(raw_input("Enter a number: "))
with open("num_list.txt", "w") as output:
for x in xrange(1, num+1):
output.write(str(x) + "\n")
def read_num():
with open("num_list.txt") as f:
numbers = map(int, f)
for number in numbers:
print number
return numbers
def main():
write_num()
print sum(read_num())
main()
For this function I am supposed to read a file with 12 random numbers. Then I am supposed to output the numbers 1 per line and finally the program is supposed to separate the even numbers and the odds then add them up and display their totals. The problem here is that even though I am getting printing of the numbers fine, the total function in the end is messing up and giving incorrect totals.
def main():
infile = open('numbers.txt','r')
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()
line4 = infile.readline()
line5 = infile.readline()
line6 = infile.readline()
line7 = infile.readline()
line8 = infile.readline()
line9 = infile.readline()
line10 = infile.readline()
line1 = line1.rstrip('\n')
line2 = line2.rstrip('\n')
line3 = line3.rstrip('\n')
line4 = line4.rstrip('\n')
line5 = line5.rstrip('\n')
line6 = line6.rstrip('\n')
line7 = line7.rstrip('\n')
line8 = line8.rstrip('\n')
line9 = line9.rstrip('\n')
line10 = line10.rstrip('\n')
print(line1)
print(line2)
print(line3)
print(line4)
print(line5)
print(line6)
print(line7)
print(line8)
print(line9)
print(line10)
line = infile.readline()
total = 0
evenTotal = 0
oddTotal = 0
while line != '':
total += int(line)
if int(line) % 2 == 0:
evenTotal += int(line)
else:
oddTotal += int(line)
line = infile.readline()
print("=======================================")
print('The total for the even numbers is', evenTotal)
print("=======================================")
print('The total for the odd numbers is', oddTotal)
infile.close()
main()
Here's are the contents from the file
47
64
67
40
91
98
82
2
42
84
48
96
I am only getting 0 for both the totals somehow.
Can someone help with this?
The file object returned by open maintains a pointer to where you are currently in a file. Each time you call infile.readline() it is advancing that pointer to the next line.
Because in the process of testing your code you're reading each line (and printing it) in advance, when you get to the later code that counts the values of the lines your file has already reached the end and will not magically go back to the beginning of the file.
You can either reopen the file, or more simply use infile.seek(0) to return the file pointer to the beginning of the file.
You have two errors in your code,
first you read your file line by line, reaching the end of file, and later you try to read further... that's impossible, you have to rewind your file, as explained in Iguananaut's answer.
your approach is, well, unusual... in general files are not read so explicitly, line1, line2, etc --- you want to be more generic so that your solution of a programming problem results more general.
Of course there are a number of things you don't know about the manner Python deals with files, as the only thing you appear to know is the .readline method, that you abused a little. One really important thing about files is that file objects (what is returned by a open) are iterables, that is you can use them in a for loop (e.g., line 5 below), and the object that you have to deal with in every iteration is a line of text. That said, you can organize your code as follows
# initialize your accumulators
odds = 0 ; evens = 0
# read lines from your file simply iterating on the file object!
for line in open('numbers.txt'):
# the int function ignores the white space, no need to strip
n = int(line)
% now you can print n
print(n)
# with an if...else... we update the accumulators
if n%2: # n is odd
odds += n
else:
evens += n
# we have read a line, converted in an integer, printed it,
# we updated the sums, we have done everything, hence
# we dedent the code, meaning that we are out of the loop
total = evens+odds
print("The sum of all even numbers is", evens)
...
You should learn to use list comprehensions or loops instead...
infile = open('numbers.txt','r')
numbers = [int(line) for line in infile]
evens = [num for num in numbers if num % 2 == 0]
odds = [num for num in numbers if num %2 == 1]
You should be able to do the rest with the code you have, however note that sum([1,2,3,4,5]) returns 15!
#Iguananaut provided you with an answer to your issue. Here's a solution to the problem stated in the question, to show how it can be done.
For this function I am supposed to read a file with 12 random numbers. Then I am supposed to output the numbers 1 per line and finally the program is supposed to separate the even numbers and the odds then add them up and display their totals.
total = [0, 0] # even, odd
with open('numbers.txt') as file:
for n in map(int, file): # read integers from the file, 1 per line
print(n) # "output the numbers 1 per line"
total[n & 1] += n # "separate the even .. and the odds then add them"
print("Even total: {}, odd total: {}".format(*total)) # "display their totals"