简体   繁体   中英

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.

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))

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])

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()])

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM