How to print specific lines from a text file in python - python

Ive made code that lets me write in numbers in lines, but now, out of all the numbers i get I have to make the comp. print the ones that are nicely divisible by 2 So far this is what ive got:
i = 0
x = 1
y = 0
z = 20
My_file = open("Numbers", 'w')
while i < z:
My_file.write(str(x))
My_file.write("\n")
x = x + 1
i = i + 1
My_file.close()
i = 0
My_file = open("Numbers", 'r')
for line in My_file:
if int(My_file.readline(y)) % 2 == 0:
print(My_file.readline(y))
y = y + 1
The top part work, my problem is the one int(My_file.readline(y)) % 2 == 0 is crap, it says:
invalid literal for int() with base 10: ''.

Each line contains a line break ("2\n"), you need to remove \n before converting to number:
...
My_file = open("Numbers", 'r')
for line in My_file:
line = line.strip() # removes all surrounding whitespaces!
if int(line) % 2 == 0:
print(line)
y = y + 1
Out:
2
4
6
8
10
12
14
16
18
20

Based on previous answers, here's a fully working example:
start_value = 1
max_value = 12
filename = "numbers"
with open(filename, "w") as my_file:
value = start_value
while value <= max_value:
my_file.write(f"{value}\n")
value += 1
with open(filename, "r") as my_file:
lines = my_file.readlines()
for line in lines:
line = line.strip()
if int(line) % 2 == 0:
print(line)
This code makes use of the "context manager" of python (the with keyword). Used with open(), it handles nicely the closing of the file.
Your error came from a \n at the end of each number. The conversion from str to int didn't work because the interpreter couldn't find out how to convert this character.
As a good practice, use meaningful variables names, even more when you ask questions here: it helps people understanding the code faster.

Does this help:
MAXINT = 20
FILENAME = 'numbers.txt'
with open(FILENAME, 'w') as outfile:
for i in range(1, MAXINT+1):
outfile.write(f'{i}\n')
with open(FILENAME) as infile:
for line in infile:
if int(line) % 2 == 0:
print(line, end='')

This works:
FILE_NAME = 'Numbers.txt'
MAX_NUMBER = 20
with open(FILE_NAME, 'w') as file:
numbers = list(map(str, range(MAX_NUMBER)))
for n in numbers:
file.write(n)
file.write('\r')
with open(FILE_NAME, 'r') as file:
for number in file:
if int(number) % 2 == 0:
print(number, end='')
Output:
0
2
4
6
8
10
12
14
16
18

Related

Getting average score from a text file in python?

I'm looking to have the program read a text file that is formatted like this for example.
Kristen
100
Maria
75
Frank
23
Is there anyway in python to skip lines and have it read only the numbers, accumulate them, and average them out? Could be more numbers or less numbers than the example above. I'm very much stuck.
you can use re.findall to find all numbers in a string:
import re
if __name__ == "__main__":
numbers = []
with open("./file.txt", "r") as f:
for line in f:
line = line.strip()
temp = list(map(lambda x: eval(x), re.findall(r'\d+', line)))
numbers += temp
average = sum(numbers) / len(numbers)
print(average)
This is the method I would use:
def get_average(filepath):
total = 0.0
with open(filepath, 'r') as f:
lines = f.readlines()
numbers = 0
for line in lines:
try:
number = int(line.strip())
total += number
numbers += 1
except:
continue
return total / float(numbers)
get_average("path/to/file.txt")
use strip to get rid of newline and isdigit to check for digit
In [8]: with open('a.txt', 'r') as f:
...: s = [int(i.strip()) for i in f if i.strip().isdigit()]
...:
In [9]: sum(s)/len(s)
Out[9]: 66.0
# assuming a score always follows a players name.
with open("path_to_file.ext", "r") as inf:
print(inf.readlines()[1::2]) # Do something with the result
# only grabbing lines that can be interpreted as numbers
with open("path_to_file.ext", "r") as inf:
for _ in inf.readlines():
if _.rstrip().isnumeric():
print(_.rstrip()) # Do something with the result
If the file name 'file.txt'
total = 0
i = 0
with open('file.txt', 'r') as file:
for line in file:
try:
total += int(line)
i += 1
except:
continue
average = total / i

how to shift values to the next line in a txt file

I have a txt file with floats separated by blank space I need to to keep only 4 elements in each line. I tried to calculate blankspace. Now i need to shift the rest of the values to the next line and restart.
fname = open("file.txt", 'r')
text = fname.read()
countBlank=0
for line in text:
for char in line:
if char.isspace():
countBlank += 1
if countBlank ==4
You can do it by converting your data and storing it in an array then you can output it to a new file like this:
import numpy as np
fname = open("file.txt", 'r')
text = fname.read()
arr = np.array(text.split())
rows = len(arr) // 4
remain = len(arr) % 4
out = np.full((rows+1, 4), None).astype(float)
out[:rows, :] = arr[:-remain]
out[rows, :remain] = arr[len(arr)-remain:]
np.savetxt('file2.txt', out)
Try this, works for me.
floatlist = fname.read().split(" ")
count = 0
finalstring = ""
for x in floatlist:
count += 1
if count == 4:
finalstring += x + "\n"
else:
finalstring += x + " "
Input:
"1 2 3 4 5 6 7 8"
Output:
"1 2 3 4
5 6 7 8"
How to write into file: (on the end of the existing code)
fname.close()
fname = open("file.txt", "w")
fname.write(finalstring)
fname.close()

Reading a file and using a loop to output the integers while displaying the largest number python

The program should output all of the integers, one per line, with no blank lines between each line. This program should also output the largest random number that was on file.
myfile = open('mynumbers.txt', 'r')
lines = myfile.readline()
print(lines)
I have gotten that far and I'm stuck. I have literally been sitting here for 6 hours and I don't know what the deal is!
I need help using a loop to read and process the mynumbers.txt file and then it also has to display the largest number that was in the group.
myfile = open('mynumbers.txt', 'w')
import random
num = random.randint(6, 12)
print(num)
for num in range(num):
myfile.write(str(random.randrange(10, 20)))
I also keep getting this error after I try everything.
ValueError: invalid literal for int() with base 10: '16 19 11 18 14 11 15 18 18 16 20 16'
Sorry everyone i'm new to the site!
.readline() only read one line.
You should use .readlines() if you want to get all the lines of your file.
Moreover, it is better to open your file using with.
with open('filename.txt') as fp:
lines = fp.readlines()
# Do something with the lines
See the documentation for more information.
use myfile.readlines() instead of myfile.readline()
max = lines[0]
for line in lines:
print line
print "MAX : ", max([int(line) for line in lines])
First of all, in your write code, you should be using
myfile.write(str(random.randrange(10, 20)) + '\n')
The reason you are getting an error message is because all of your numbers are being written to the same line.
If you want to keep your write code then use the following.
with open('mynumbers.txt', 'r') as myfile:
line = myfile.readline()
nums = line.split(' ')
# Set first number as the max
max = int(nums[0])
# Converting to int will remove trailing newline
print(max)
# Go through the rest of the numbers
for i in range(1, len(nums)):
x = int(nums[i])
print(x)
# Check max
if x > max:
max = x
print("Max = " + str(max))
else use this after changing the write code.
with open('mynumbers.txt', 'r') as myfile:
# Put each line into an array
lines = myfile.readlines()
# Set first number as the max
max = int(lines[0])
# Converting to int will remove trailing newline
print(max)
# Go through the rest of the numbers
for i in range(1, len(lines)):
x = int(lines[i])
print(x)
# Check max
if x > max:
max = x
print("Max = " + str(max))
I would recommend
max([int(l) for l in myfile.readlines()])
edit:
according to your file format, something like this will probably work
max([int(l) for l in myfile.readline().split()])
Your sample file creation script will cause all of your numbers to be created as one long line. You would need to add a newline after each write.
myfile = open('mynumbers.txt', 'w')
import random
num = random.randint(6, 12)
print(num)
for num in range(num):
myfile.write("%s\n" % random.randrange(10, 20))
The following will produce the answer you want. Contrary to other suggestions, I would recommend also learning about processing such files a line at a time as this would scale better. Say in the future your test file was huge, then attempting to read the whole file in could result in you running out of memory to process it. By loading the file a line at a time, it would be able to cope with any size.
max_value = None
with open('mynumbers.txt', 'r') as myfile:
for line in myfile:
num = int(line)
if max_value:
max_value = max(max_value, num)
else:
# Use the first value as the initial max value
max_value = num
if max_value:
print("Max value: %u" % max_value)
else:
print("No numbers found")
Python2 If this is what you have in your text file:16 19 11 18 14 11 15 18 18 16 20 16
You can find the largest number like this:
fname = 'mynumbers.txt'
fhand = open(fname)
for line in fhand:
line = line.rstrip()
num =[int(s) for s in line.split(' ')]
print max(num)
Output:
20
To print all the numbers:
for i in num:
print i
Output:
16
19
11
18
14
11
15
18
18
16
20
16

Why does this variable an empty sequence?

The code i am using is selecting the highest number out of three in a text file set out as
R 3 5 7
F 2 9 6
I 6 3 5
When it is run it does wright the correct infomation to the text file but comes up with
max_in_line = max(nums)
ValueError: max() arg is an empty sequence
my code is
with open (classno, 'r') as f, open("class11.txt", 'w') as fout:
for line in f.readlines(): #does right swaps around
if not line.strip(): continue
parts = line.split()
nums_str = line.split()[1:]
nums = [int(n) for n in nums_str]
max_in_line = max(nums)
print (max_in_line)
print (line)
score = (max_in_line)#same problem
name = (parts[0])
fout.write(("\n") + str(score) + (" ") + (name))
fout.close
f.close#it does write them but comes up with the problem
Try this code, just skip the empty line or empty element in the list:
with open ('classno.txt', 'r') as f, open("class11.txt", 'w') as fout:
lines = [line.strip() for line in f]
for line in lines:
splitted = [i for i in line.split(' ') if i]
nums = splitted[1:]
max_nums = max(map(int, nums))
name = splitted[0]
fout.write('\n' + str(max_nums) + ' ' + name)
It works for me, hope helps.

Calculating average of numbers in a file

So what I have to do is figure out how to ask a user for a a text file and output the average of all the numbers. By tinkering around I have figured out how to find the average of a list i made but not sure how to do a list that the user give me. This is what I have right now:
with open('average', 'wt') as myFile:
myFile.write('3\n')
myFile.write('45\n')
myFile.write('83\n')
myFile.write('21\n')
with open('average', 'rt') as myFile:
total, n = 0, 0
for line in myFile:
total += int(line)
n += 1
print(float(total) / n)
Supposing that there is one number on each line of the file:
with open(input('Filename: '), 'r') as f:
numbers = [int(a.strip()) for a in f]
print('Average is {}'.format(sum(numbers)/len(numbers)))
Something like this?
import string
fileName = raw_input("What file name: ")
lines = []
try:
file = open(fileName)
lines = file.readlines()
file.close()
except:
print "Unable to open file"
sum = 0
values = 0
if(len(lines) > 0):
for line in lines:
value = 0
try:
value = int(string.strip(line))
except ValueError:
pass
if(value != 0):
sum = sum + value
values += 1
print "Average = %f for %d lines, sum = %f"%(sum/values,values,sum)
else:
print "No lines in the file"
NOTE: This assumes one number per line. It will not count blank lines or lines that have text. Other than that, junk on the lines or a bad file should not cause an exception, etc.
This was the test file (there are blank lines):
10
20
30
40
50
23
5
asdfadfs
s
And the output:
What file name: numbers.txt
Average = 25.000000 for 7 lines, sum = 178.000000

Categories