A oberholzer
A oberholzer

Reputation: 23

Opening multiple text files at once

Hi guys I'm currently trying to open multiple text files depending on an input from a user, but i cant figure out how to. Im opening the files and then sorting them into a dictionary any help is appreciated!

this is my code:

ans = int(input('How many days of data do you have? '))  
temps1 = open('temps1.txt')    
temps2 = open('temps2.txt')  
temps3 = open('temps2.txt')  
for line in temps1: '  

e.g if ans = 3 open temps1, temps2 and temps3, etc

Also i'm unable to divide a number by 4 and then put it into a dictionary with the decmical intact

num = int(num)  
num = num/4  
f[room] = f.get(room, 0) + int(num)  

when i run this e.g if num is equal to 25 it divides by 4 making 6.25 when i put it into the dictionary it just becomes 6. Thanks!

Upvotes: 0

Views: 87

Answers (3)

Rohi
Rohi

Reputation: 814

First request :

file_dict = {}
ans = int(input("How many files would you want to open?"))
foreach file_num in range(0, ans):
    file_name = "temps" + str(file_num) + ".txt"
    file_dict[file_name] = open(file_name)

You will recieve a dict with keys = "file_name", and values = file handler.

Do take in account that this code has 0 'checking' statments.

Second request:

The reason your number turns from 6.25 to 6 is because you turned it into an int("int(num")), this is because integers can not contain decimal values.

Was a bit difficult understanding exactly what you wanted, so let me know if I misunderstood something.

Upvotes: 0

Lricsi
Lricsi

Reputation: 36

You should not convert your num into int - as it won't let you have the fractional part.

Upvotes: 1

abc
abc

Reputation: 11929

You can use the with statement with multiple open().

with open('temps1.txt') as f1, open('temps2.txt') as f2, open('temps3.txt') as f3:
    pass

Upvotes: 2

Related Questions