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.
Related
Im working on some python assignments for class and I cannot answer this question. I cannot find the error in my code. The error I receive is TypeError: 'function' object is not iterable. The question is:
a. Random Number File Writer Function
Write a function that writes a series of random numbers to a file called "random.txt". Each random number should be in the range of 1 through 500. The function should take an argument that tells it how many random numbers to write to the file.
b. Random Number File Reader Function
Write another function that reads the random numbers from the file "random.txt", displays the numbers, then displays the following data:
The total of the numbers
The number of random numbers read from the file
c. Main Function
Write a main function that asks the user about how many random number the user wants to generate. It them calls the function in a. with the number the user wants as an argument and generates random numbers to write to the file. Next, it calls the function in b.
Here is my code:
import random
def random_Write(num):
# Open a file for writing
file_w = open('random.txt', 'w')
for i in range(0,num):
rand = random.randrange(1,501)
file_w.write(str(rand) + '\n')
#closing file
file_w.close()
def random_Read():
# Reading from file
readFile = open('random.txt', 'r')
count = 0
total = 0
for lines in random_Read:
count +=1
total += float(lines)
print ('number count: ', str(count))
print ('The numbers add up to: ', str(total))
readFile.close()
def main():
num = int(input("How many numbers would you like to generate?: "))
random_Write(num)
random_Read()
main()
Quite simple actually, in random_Read(), in the for loop, instead of for lines in random_Read: put in for lines in readFile.readlines(): Why are you getting the error? because of a simple typo because you said random_Read which is the function...
Your function random_Read has some mistakes. Here is a corrected version:
def random_Read():
#Reading from file
readFile = open('random.txt', 'r')
count = 0
total = 0
#You were looping with random_Read. I changed to readFile.readlines()
#so you get a list with all of the lines of the file.
for lines in readFile.readlines():
count +=1
total += float(lines)
print ('number count: ', str(count))
print ('The numbers add up to: ', str(total))
#only call .close() once, at he end of the function
readFile.close()
i would like to generate random numbers and write them to a .txt file.
The range is : str(random.randint(0,10))
Before it generates me a random number my code should first check the .txt file. In this text file are already written down some random numbers. If the random number already exists it should generate me a new one and add it to my .txt file.
randomTxt = './random.txt'
def checkRandomNumberExists(value):
with open(randomTxt, 'a+') as random:
genRandom = str(random.randint(1,10))
if value in random:
random.write(genRandom)
random.write('\n')
I quess i am on the wrong way.
Can anyone please help me.
Thank you in advance
I don't see any reason to use argument in function because you're generating random number and you are generating random number between 1-10, what if all number is added in the text should it add number other than 1,2,3...10, please edit you question and mention that.
Below code will check if number is present in the text file or not, it will add the number in text file if it's not present else it will print the message that number already exits.
Code
import random
lines = []
num = random.randint(0,10)
f= open("random.txt","w+")
def checkRandomNumberExists():
with open("random.txt") as file:
for line in file:
line = line.strip()
lines.append(line)
if str(num) not in lines:
with open("random.txt", "a") as myfile:
myfile.write(str(num)+'\n')
print(str(num)+ ' is added in text file')
else:
print(str(num)+ ' is already exists in text file')
checkRandomNumberExists()
Output when inserted new value
7 is added in text file
Output when value is already in text file
7 is already exists in text file
Try using a while loop inside:
randomTxt = './random.txt'
with open(randomTxt, 'a+') as file:
text = file.read()
genRandom = str(random.randint(1,10))
while genRandom in text:
genRandom = str(random.randint(1,10))
file.write(genRandom)
file.write('\n')
Note: Please do not name files and variables a builtin name (i.e random) because it might override the original module.
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 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.
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()