mgale
mgale

Reputation: 15

Read a file of numbers into a tuple in python?

I have a file that has numbers like this in it:

5

10

15

20

I know how to write code that reads the file and inputs the numbers into a LIST but how do I write code that reads the file and inputs the number in a TUPLE if a tuple doesnt support the append function? this is what I got so far:

filename=input("Please enter the filename or path")
file=open(filename, 'r')
filecontents=file.readlines()
tuple1=tuple(filecontents)
print(tuple1)

the output is this:

('5\n', '10\n', '15\n', '20\n')

it should be this:

5,10,15,20

Upvotes: 1

Views: 2066

Answers (4)

Hemerson Tacon
Hemerson Tacon

Reputation: 2522

If you already know how to make a list of ints, just cast it to a tuple like what you are doing in your attempt to solve the problem.

Here a map object can also se casted to a tuple, but it also works with list:

filename=input("Please enter the filename or path: ")
with open(filename, 'r') as file:
    filecontents=tuple(map(int, file.read().split()))

print(filecontents)

Also, if you use with statement you don't need to worry about closing the file (you was missing that part in your code too)

Upvotes: 0

BernardL
BernardL

Reputation: 5434

Using with open(..) is recommended to make sure the file is closed once you are done with it. Then use an expression to transform the returned list to a tuple.

filename=input("Please enter the filename or path")
with open(filename, 'r') as f:
    lines = f.readlines()

tup = tuple(line.rstrip('\n') for line in lines)
print(tup)

Upvotes: 1

Smasho
Smasho

Reputation: 1180

If you are sure they are integers, you can do something like:

filename=input("Please enter the filename or path")
with open(filename, 'r') as f:
    lines = f.readlines()

result = tuple(int(line.strip('\n')) for line in lines)
print(resultt)

Also, if you have a list, you can always convert it to a tuple:

t = tuple([1,2,3,4])

So you can build the list appending elements, and finally convert it to a tuple

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71580

Try this:

s=','.join(map(str.rstrip,file))

Demo:

filename=input("Please enter the filename or path: ")
file=open(filename, 'r')
s=tuple(map(str.rstrip,file))
print(s)

Example output:

Please enter the filename or path: thefile.txt
(5,10,15,20)

Upvotes: 1

Related Questions