Instructions:
Write a program that writes a series of random numbers to a file.
Each random number should be in the range of 1 through 100.
The application should let the user specify how many random numbers the file will hold.
Here's what I have:
import random
afile = open("Random.txt", "w" )
for line in afile:
for i in range(input('How many random numbers?: ')):
line = random.randint(1, 100)
afile.write(line)
print(line)
afile.close()
print("\nReading the file now." )
afile = open("Random.txt", "r")
print(afile.read())
afile.close()
A few problems:
It's not writing the random numbers in the file based on the range the user is setting.
The file can't close once opened.
When the file is read, nothing.
While I thought the set up was okay, it seem to always get stuck on execution.
Get rid of for line in afile:, and take out what was in it. Also, because input returns a string in Python 3, convert it to an int first. And you are trying to write an integer to a file, when you have to write a string.
This is what it should look like:
afile = open("Random.txt", "w" )
for i in range(int(input('How many random numbers?: '))):
line = str(random.randint(1, 100))
afile.write(line)
print(line)
afile.close()
If you are worried that the user might input a non-integer, you can use a try/except block.
afile = open("Random.txt", "w" )
try:
for i in range(int(input('How many random numbers?: '))):
line = str(random.randint(1, 100))
afile.write(line)
print(line)
except ValueError:
# error handling
afile.close()
What you were trying to do was iterate through the lines of afile, when there were none, so it didn't actually do anything.
import random
ff=open("file.txt","w+")
for _ in range(100):
ff.write(str(random.randrange(500,2000)))
ff.write("\n")
ff.seek(0,0)``
while True:
aa=ff.readline()
if not aa:
print("End")
break
else:
if int(aa)%2==0:
print(int(aa))
ff.close()
Related
I try to output the sum of 1 - 12 lines which contain each two numbers which are seperated by ' '. Because I don't know how many lines will be inputed, I have an endless loop, which will be interupted if the line is empty. But if there is no input anymore, there won't be any empty input and the program is stuck in the input function.
while True:
line = input()
if line:
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
else:
break
So after the last outputed sum I want the program to stop. Maybe it is possible with a time limit?
It looks like the automated input is coming in via sys.stdin. In that case you can just read from the standard input stream directly. Try this:
def main():
import sys
lines = sys.stdin.read().splitlines()
for line in lines:
print(sum(map(int, line.split())))
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
With an input of "1 2\n3 4" to the sys.stdin stream, this script prints 3 and 7.
For the case without timeout, and the case allowing you to capture the content (which is usually handy).
The following code has been tested in HACKERRANK. I am sure HackerEarth is the same.
contents = []
while True:
try:
line = input()
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
except EOFError:
break
contents.append(line)
if you don't care about the input.
while True:
try:
line = input()
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
except EOFError:
break
Doing this exercise from ThinkPython and wanting to do a little extra, trying to modify the exercise function (avoid) to prompt the user repeatedly and perform the calculation to find how many words in a text file (fin) contain the user inputted letters (avoidprompt). It works the first time but after it prompts the user for input again it always returns an answer of 0 words.
Feel like the most likely issue is I'm misunderstanding how to use the while loop in this context since it works the first time but doesn't after that. Is there a better way?
fin = open('[location of text file here]')
line = fin.readline()
word = line.strip()
def avoid(word, forbidden):
for letter in word:
if letter in forbidden:
return False
return True
def avoidprompt():
while(True):
n = 0
forbidden = input('gimmie some letters n Ill tell u how many words have em. \n')
for line in fin:
if avoid(line, forbidden) == False:
n = n+1
print('\n There are ' + str(n) + " words with those letters. \n")
When you open a file and do for line in file, you've consumed the entire file.
There are two easy solutions:
1) Go back to the start of the file in each iteration of your while(True) loop, by doing fin.seek(0)
2) Just store the file contents in a list, by replacing the first line of your script with fin = open('file.txt').readlines()
I believe you need to do something along these lines:
def avoidprompt():
while(True):
n = 0
fin.seek(0)
forbidden = input('gimmie some letters n Ill tell u how many words have em. \n')
for line in fin:
if avoid(line, forbidden) == False:
n = n+1
print('\n There are ' + str(n) + " words with those letters. \n")
Seek sets your pointer back to a specific line in an open file and since you aleady iterated through the file once, your cursor needs to be brought back to the top of the file in order to reread words
You can see this other stack overflow for more details here
Hope this helps! You used the loop just fine
I've currently got an issue where I need to read N lines from a text file,
there is 50 lines total, but I want to give my user the choice of how many are picked.
I don't know where to start.
Try this:
user_demand = int(input('how many lines?'))
if user_demand > 50:
user_demand = 50
with open('filename.txt', 'rb') as file:
for i, line in enumerate(file):
if i == user_demand:
break
print(line)
So first of all you have to open the file:
txt = open(r"yourfile.txt","r")
Now you can read it.
lines = 0
for line in txt:
if lines >= max_lines: break #max_lines is the input by the user
#do something
lines = lines + 1
txt.close()
Or you could use readline() to store all lines in an Array and then just print or use the amount of lines the user wants to.
Note: There are a lot of better and more efficent solutions to this task. This ist jsut a "Quick-Start" for you :)
You could do something like this:
# open the file
file = open("filename.txt")
# load lines into a list
all_lines = file.readlines()
# get input
amount_lines = input("How many lines do you want to print? ")
# turn input (string) into an integer
amount_lines_int = int(amount_lines)
# do something with all the lines from index 0 to index amount_lines_int (excl.)
for line in all_lines[:amount_lines_int]:
# strip line frome whitespace (i.g. the paragraph)
line = line.strip()
print(line)
file.close()
I have the very simple task of creating a text file with 8 random integers from 1-100, reading the file, displaying the numbers on the same line, calculating the even integers and the odd integers, and then displaying them.
The problem I am having is getting the string to display on the same line. I have browsed multiple articles about similar problems to no avail. I have attempted to use .join, however, it seems to break the code when I include it.
# Imports random and time
import random
import time
# Defines the main function
def main():
# Opens file "mynumbers" and creates it if not existent
myfile = open('mynumbers.txt', 'w')
# Statement to write intergers to text file in the correct format
for count in range(8):
number = random.randint(1, 100)
myfile.write(str(number) + '\n')
# Defines read function
def read():
# Opens the "mynumbers" file created in the main function
myfile= open('mynumbers.txt', 'r')
# Sets the content variable to the content of the file that was opened
content = myfile.read()
# Prints the content variable and strips the \n from the string
stripit = content.rstrip('\n')
print(stripit)
# Calls for the functions, prints created, and sleep calls
main()
print('File Created!')
time.sleep(1)
read()
time.sleep(5)
Any help that can be provided would be greatly appreciated.
Your read function is reading the whole file contents into a single string. Your rstrip call on that string removes the last newline from it, but not any of the internal newlines. You can't effectively use str.join, since you only have the one string.
I think there are two reasonable solutions. The first is to stay with just a single string, but replace all the internal newlines with spaces:
def read():
myfile = open('mynumbers.txt', 'r')
content = myfile.read()
stripit = content.rstrip('\n')
nonewlines = stripit.replace('\n', ' ')
print(nonewlines)
The other approach is to split the single string up into a list of separate strings, one for each number. This is more useful if we need to do different things with them later. Of course, all we're going to do is use join to combine them back together:
def read():
myfile = open('mynumbers.txt', 'r')
content = myfile.read()
content_list = content.split() # by default, splits on any kind of whitespace
rejoined_content = " ".join(content_list)
print(rejoined_content)
Don't add a newline char when you write the file. Just use a space instead (or comma, whatever)
import random
import time
#Defines the main function
def main():
#Opens file "mynumbers" and creates it if not existent
myfile = open('mynumbers.txt', 'w')
#Statement to write intergers to text file in the correct format
for count in range(8):
number = random.randint(1,100)
myfile.write(str(number) +' ')
#Defines read function
def read():
#Opens the "mynumbers" file created in the main function
myfile= open('mynumbers.txt', 'r')
#Sets the content variable to the content of the file that was opened
content=myfile.read()
#Prints the content variable and strips the \n from the string
print(content)
#Calls for the functions, prints created, and sleep calls
main()
print('File Created!')
time.sleep(1)
read()
time.sleep(5)
the code looks great but do this instead on your read() function.
def read():
my_numbers = []
with open('mynumbers.txt', 'r') as infile:
for line in infile:
line = line.strip()
my_numbers.append(line)
print (' '.join(line))
I would do it like this, especially because you mentioned the even and odd part that you'll need to do next. At the end of the first loop, you'll have a list of ints (rather than strs) that you can work with and determine whether they are even or odd.
def read():
my_nums = []
with open('mynumbers.txt', 'r') as f:
for line in f:
num_on_line = int(line.strip())
my_nums += [num_on_line]
print num_on_line, #don't forget that comma
for num in my_nums:
#display the even and odds
You could print the numbers in a single line in this way
with open('mynumbers.txt', 'r') as numbers_file:
for line in numbers_file:
print(line.strip(), end=" ")
The line.strip() is for eliminate the \n character.
This program generates a user defined amount of random numbers and then writes to a file. The program works fine as written, but i want the text file use \n to concatenate. What am I doing wrong?
#This program writes user defined
#random numbers to a file
import random
randfile = open("Randomnm.txt", "w" )
for i in range(int(input('How many to generate?: '))):
line = str(random.randint(1, 100))
randfile.write(line)
print(line)
randfile.close()
Add "\n":
import random
randfile = open("Randomnm.txt", "w" )
for i in range(int(input('How many to generate?: '))):
line = str(random.randint(1, 100)) + "\n"
randfile.write(line)
print(line)
randfile.close()
You could also make use of Python 3's print function's file keyword argument:
import random
with open("Randomnm.txt", "w") as handle:
for i in range(int(input('How many to generate?: '))):
n = random.randint(1, 100)
print(n, file=handle)
print(n)
# File is automatically closed when you exit the `with` block
file.write() simply writes text to a file. It does not concatenate or append anything, so you need to append a \n yourself.
(Note that the type would be called _io.TextIOWrapper in Python 3)
To do this, simply replace
line = str(random.randint(1, 100))
with
line = str(random.randint(1, 100))+"\n"
This will append a newline to every random number.