-2

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!

stevendoe
  • 33
  • 4
  • 2
    what data is in your input file? One Integer per line? Also, to read files , see [link](http://stackoverflow.com/questions/31109951/python-cannot-open-a-text-file) – Vaulstein Jun 29 '15 at 07:35
  • You can give sample data for input file, then it will be helpful – Nilesh Jun 29 '15 at 07:37
  • 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))) – stevendoe Jun 29 '15 at 07:38
  • Can you give a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) about what you want to do? or a part of your input? also pls add your code to question! – Mazdak Jun 29 '15 at 07:38
  • What output you got from your code? What you expecting ? – Nilesh Jun 29 '15 at 07:42
  • 1
    The problem is with your write code. `myfile.write(str(random.randrange(10, 20)) + '\n')` Your ints are all on the same line. – Dobz Jun 29 '15 at 08:16

6 Answers6

0

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

Delgan
  • 18,571
  • 11
  • 90
  • 141
0

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))
Dobz
  • 1,213
  • 1
  • 14
  • 36
  • it's still giving me this error ValueError: invalid literal for int() with base 10: '16 19 11 18 14 11 15 18 18 16 20 16 ' – stevendoe Jun 29 '15 at 11:49
  • @stevendoe I saw your comment down further saying you got it. It would be good if you could accept an answer, if one of them worked for you :) – Dobz Jun 29 '15 at 15:59
  • i know i tried but i have to have a 15 reputation or something – stevendoe Jul 02 '15 at 15:45
0

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])
shaktimaan
  • 1,769
  • 13
  • 14
  • I've tried all of these and I keep getting an error back. – stevendoe Jun 29 '15 at 07:50
  • ValueError: invalid literal for int() with base 10: '16 19 11 18 14 11 15 18 18 16 20 16 ' – stevendoe Jun 29 '15 at 07:50
  • It's not a fault of @shaktimaan , but yours, because you didn't specify the file format well enough! – hellow Jun 29 '15 at 08:13
  • Oh!! I checked your code for writing to file. The cause for this error may be because you are not putting `\n` at the end of each line. Just add this part while adding data to your file `myfile.write(str(random.randrange(10, 20)) + "\n")` – shaktimaan Jun 29 '15 at 08:58
0

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()])
hellow
  • 12,430
  • 7
  • 56
  • 79
  • ValueError: max() arg is an empty sequence – stevendoe Jun 29 '15 at 08:22
  • Sorry, but if you aren't able to specify the format of your file well enough, nobody can help you. Either you will edit your post or delete it and learn python on your own. – hellow Jun 29 '15 at 08:28
0

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
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48
  • 16 19 11 18 14 11 15 18 18 16 20 16 this is what is in my file text – stevendoe Jun 29 '15 at 08:20
  • @stevendoe ok, in that case, I updated my answer. If you don't have a commas between the numbers, then you just have to `split(' ')` on space. My code is updated so it will woke for you now. – Joe T. Boka Jun 29 '15 at 08:31
0

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")
Martin Evans
  • 45,791
  • 17
  • 81
  • 97