i want to input the file name in this case books.txt and get the lines but i cant get it work, i have the files in the same directory but when i run this nothing happens, any way to fix this? or to call that function in another .py file
books.txt 7,1,2,3,4,3 2,6,1,3,1
file_name = input("type the file name: ") def read_txt(file_name) file = open(file_name, "r") lines = file.readlines() file.close() return lines read_txt(file_name)
but this return nothing and i dont know what to do :(
Advertisement
Answer
You need to add this line to the end, so it actually prints out the values:
print(read_txt(file_name))
So the full code would be (I also changed some code as the OP said what to change):
file_name = input("type the file name: ") def read_txt(file_name): file = open(file_name, "r") lines = [x for i in file.readlines() for x in list(map(int, i.strip().split(',')))] file.close() return lines print(read_txt(file_name))
Output:
[7, 1, 2, 3, 4, 3 2, 6, 1, 3, 1]