Reputation: 21
I am writing a python script that by means of a path takes the .txt extension files and lists them and so the user selects by means of the number assigned to each file, and the file that he wants to open and the program must open it and read it .
I already have the script to take the .txt extension files and list them, the error that appears is that it does not let me take the file that the user selected.
import os
mi_ruta = os.getcwd()
archivos = os.listdir(mi_ruta)
cont = 0
for i in range(len(archivos)):
if (archivos[i][-3:] == 'txt') or (archivos[i][-3:] == 'csv'):
print(i,archivos[i])
cont = cont + 1
n = -1
while n >= len(archivos) or n < 0:
print("Ingrese un valor entre",0,"y" , cont-1 )
try:
n = int(input("Digite el número del archivo que quiere abrir: "))
except:
print("Ingrese valor numerico")
print("El archivo selecionado es: ",archivos[n])
file = open("m", "r")
file.close()
Upvotes: 0
Views: 1041
Reputation: 1098
file = open(archivos[n]), "r”)
print(file.read()) # if you want to see it
And one more problem: When there are other files (.py, .pdf), it tells me that it's not possible to select larger numbers, for example:
5 alph.txt
10 data.txt
I have 10 files, but only 2 .txt
files.
print("Ingrese un valor entre",0,"y" , cont-1)
It says “entre 0 y 2”
, but it works with 5 and 10. I would do:
print("Ingrese un valor entre", 0, "y" , len(archivas)-1)
Upvotes: 1