Just need some help with how to write code to read the total lines from 2 text files
with open('user.txt','r') as admin_file:
for line in admin_file:
total = len(admin_file.readlines())
print("Total number of users:", total)
with open('tasks.txt','r') as admin_file:
for line in admin_file:
total = len(admin_file.readlines())
print("Total number of tasks:", total)
if you remove
for line in admin_file:
from both places, the code should work.
No need to loop through the lines here. Readlines already returns the list of all lines.
Related
I'm making a stock game's python version. There are stock prices and users can buy them. I need to make a thing that shows the average price of purchases made by the user when buying more than 0 stocks. Stock prices are connected to a randomizer. That's the story. But I think I can make a smaller code and then place that code into that game's code. Here's that small code:
numA=int(input("Number 1: "))
numB=int(input("Number 2: "))
with open('average.txt','a') as avg:
avg.write(str(numA))
avg.write("\n")
avg.write(str(numB))
avg.write("\n")
How can I make a code that reads the text file and sums numA and numB without doing something like total=numA+numB. I want the program to import it from the text file because as I said, I'm making a bigger program that includes loops and I will use the text file as memory.
you can try this one :
import numpy as np
with open('average.txt','r') as avg:
lines = avg.readlines()
Sum = np.sum([int(line.rstrip()) for line in lines], axis = 0)
Do you want something like this?
with open("New Text Document.txt", "r") as file:
text = file.read()
nums = text.replace("\n", " ").split(" ")
nums = (int(i) for i in nums if i.isdigit())
total = sum(nums)
I basically read the file in read mode and stored it inside of the text variable. Then I replaced all the newlines with spaces and then split the string by spaces. Then I used a generator comprehension to check if the element I is a number and if it is, I added it to the nums generator. And finally I used sum to get the sum of the numbers inside of the nums generator.
Or you could do something like this:
with open("file", "r") as file:
try:
total = sum(map(int, file))
except ValueError:
print("File has to contain only numbers.")
Taking an intro to programming course using python.
Our task this week is to create a text file called 'randomnum.txt' and print to it using a python script. I was able to successfully create the file but am met with the second part of the assignment to print the contents of the file AND count the number of numbers (lines) in the .txt.
I have been able to print the contents or count the number of lines but never both. I'm pretty bad at Python and would like some help.
with open ('randomnum.txt','r') as random_numbers:
num_nums = 0
contents = random_numbers.read()
for lines in random_numbers:
num_nums += 1
print('List of random numbers in randomnum.txt')
print(contents)
print('Random number count: ', num_nums)
This way it gives me a random number count of 0.
any help would be super appreciated!
This is a good question because you're observing the behaviour that you can only read a file object once. Once you call random_numbers.read(), you can not repeat that action.
What I recommend is instead of doing .read(), use .readlines(). It reads each line one-by-one instead of reading the whole file at once. While iterating through each line, add one to your counter and print the current line:
with open("file.txt", "r") as myfile:
total = 0
for line in myfile.readlines():
print(line, end="")
total += 1
print("Total: " + str(total))
Note the second parameter I pass through to print (end=""). This is because by default print adds a newline, but since the file will already have newlines at the end of the line, you would be printing two new lines. end="" stops the behaviour of print printing a trailing newline.
Try this readlines then map for stripping, using the method descriptor for it, then just use len for getting length:
with open ('randomnum.txt','r') as random_numbers:
l=random_numbers.readlines()
print('List of random numbers in randomnum.txt')
print(''.join(map(str.rstrip,l)))
print('Random number count: ', len(l))
Output of code with randomnum.txt as:
1
2
3
4
5
6
Output:
List of random numbers in randomnum.txt
123456
Random number count: 6
Calling .read() and iterating with for ... in ... both consume the contents of the file. You can't do both unless you call .seek(0) in between. Alternatively, instead of calling .read(), you could capture the lines in your for loop (maybe switch to .readlines()) and then not worry about it.
I've been trying to count the lines of a very long file (more than 635000 lines).
I've tried with:
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
and also:
num_lines = sum(1 for line in open(fname))
Both work perfectly for files with not so much lines. I've checked making a 5 lines file and works ok, output is 5.
But with with a long file, which exactly has 635474 lines, the output of both methods posted above is 635466.
I know that the file has 635474 lines, not 635466 lines because I'm creating strings inside of the file and the last two lines are:
alm_asdf_alarm635473=.NOT USED
alm_asdf_alarm635474=.NOT USED
And also because if I open the file with Notepad++ the last line is counted as 635474.
What's the logic behind this? Why is it counting less lines that the real ones?
Thanks in advance.
If all your lines have same structure, you could try a program like that :
import re
num = re.compile('[^0-9]*([0-9]+)')
delta = 1 # initial delta
with open(...) as fd:
for i, line in enumerate(fd, delta):
m = num.match(line)
if i != int(m.group(1)):
print i, "th line for number ", int(m.group(1))
break
It should be enough to find first line where you have a difference (delta is here for the case where first line would be internally numbered 1 and not 0). Then you could more easily understand where the problem really comes from with notepad++.
Note : if only some lines have this structure, you could use that variation :
m = num.match(line)
if (m is not None) and (i != int(m.group(1))):
I'm really new at python and needed help in making a list from data in a file. The list contains numbers on separate lines (by use of "\n" and this is something I don't want to change to CSV). The amount of numbers saved can be changed at any time because the way the data is saved to the file is as follows:
Program 1:
# creates a new file for writing
numbersFile = open('numbers.txt', 'w')
# determines how many times the loop will iterate
totalNumbers = input("How many numbers would you like to save in the file? ")
# loop to get numbers
count = 0
while count < totalNumbers:
number = input("Enter a number: ")
# writes number to file
numbersFile.write(str(number) + "\n")
count = count + 1
This is the second program that uses that data. This is the part that is messy and that I'm unsure of:
Program 2:
maxNumbers = input("How many numbers are in the file? ")
numFile = open('numbers.txt', 'r')
total = 0
count = 0
while count < maxNumbers:
total = total + numbers[count]
count = count + 1
I want to use the data gathered from program 1 to get a total in program 2. I wanted to put it in a list because the amount of numbers can vary. This is for an introduction to computer programming class, so I need a SIMPLE fix. Thank you to all who help.
Your first program is fine, although you should use raw_input() instead of input() (which also makes it unnecessary to call str() on the result).
Your second program has a small problem: You're not actually reading anything from the file. Fortunately, that's easy in Python. You can iterate over the lines in a file using
for line in numFile:
# line now contains the current line, including a trailing \n, if present
so you don't need to ask for the total of numbers in your file at all.
If you want to add the numbers, don't forget to convert the string line to an int first:
total += int(line) # shorthand for total = total + int(line)
There remains one problem (thanks #tobias_k!): The last line of the file will be empty, and int("") raises an error, so you could check that first:
for line in numFile:
if line:
total += int(line)
There's a text file that I'm reading line by line. It looks something like this:
3
3
67
46
67
3
46
Each time the program encounters a new number, it writes it to a text file. The way I'm thinking of doing this is writing the first number to the file, then looking at the second number and checking if it's already in the output file. If it isn't, it writes THAT number to the file. If it is, it skips that line to avoid repetitions and goes on to the next line. How do I do this?
Rather than searching your output file, keep a set of the numbers you've written, and only write numbers that are not in the set.
Instead of checking output file for the number if it was already written it is better to keep this information in a variable (a set or list). It will save you on disk reads.
To search a file for numbers you need to loop through each line of that file, you can do that with for line in open('input'): loop, where input is the name of your file. On each iteration line would contain one line of input file ended with end of line character '\n'.
In each iteration you should try to convert the value on that line to a number, int() function may be used. You may want to protect yourself against empty lines or non-number values with try statement.
In each iteration having the number you should check if the value you found wasn't already written to the output file by checking a set of already written numbers. If value is not in the set yet, add it and write to the output file.
#!/usr/bin/env python
numbers = set() # create a set for storing numbers that were already written
out = open('output', 'w') # open 'output' file for writing
for line in open('input'): # loop through each line of 'input' file
try:
i = int(line) # try to convert line to integer
except ValueError: # if conversion to integer fails display a warning
print "Warning: cannot convert to number string '%s'" % line.strip()
continue # skip to next line on error
if i not in numbers: # check if the number wasn't already added to the set
out.write('%d\n' % i) # write the number to the 'output' file followed by EOL
numbers.add(i) # add number to the set to mark it as already added
This example assumes that your input file contains single numbers on each line. In case of empty on incorrect line a warning will be displayed to stdout.
You could also use list in the above example, but it may be less efficient.
Instead of numbers = set() use numbers = [] and instead of numbers.add(i): numbers.append(i). The if condition stays the same.
Don't do that. Use a set() to keep track of all the numbers you have seen. It will only have one of each.
numbers = set()
for line in open("numberfile"):
numbers.add(int(line.strip()))
open("outputfile", "w").write("\n".join(str(n) for n in numbers))
Note this reads them all, then writes them all out at once. This will put them in a different order than in the original file (assuming they're integers, they will come out in ascending numeric order). If you don't want that, you can also write them as you read them, but only if they are not already in the set:
numbers = set()
with open("outfile", "w") as outfile:
for line in open("numberfile"):
number = int(line.strip())
if number not in numbers:
outfile.write(str(number) + "\n")
numbers.add(number)
Are you working with exceptionally large files? You probably don't want to try to "search" the file you're writing to for a value you just wrote. You (probably) want something more like this:
encountered = set([])
with open('file1') as fhi, open('file2', 'w') as fho:
for line in fhi:
if line not in encountered:
encountered.add(line)
fho.write(line)
If you want to scan through a file to see if it contains a number on any line, you could do something like this:
def file_contains(f, n):
with f:
for line in f:
if int(line.strip()) == n:
return True
return False
However as Ned points out in his answer, this isn't a very efficient solution; if you have to search through the file again for each line, the running time of your program will increase proportional to the square of the number of numbers.
It the number of values is not incredibly large, it would be more efficient to use a set (documentation). Sets are designed to very efficiently keep track of unordered values. For example:
with open("input_file.txt", "rt") as in_file:
with open("output_file.txt", "wt") as out_file:
encountered_numbers = set()
for line in in_file:
n = int(line.strip())
if n not in encountered_numbers:
encountered_numbers.add(n)
out_file.write(line)