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
JavaScript
x
6
1
books.txt
2
3
7,1,2,3,4,3
4
2,6,1,3,1
5
6
JavaScript
1
9
1
file_name = input("type the file name: ")
2
def read_txt(file_name)
3
file = open(file_name, "r")
4
lines = file.readlines()
5
file.close()
6
return lines
7
8
read_txt(file_name)
9
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:
JavaScript
1
2
1
print(read_txt(file_name))
2
So the full code would be (I also changed some code as the OP said what to change):
JavaScript
1
8
1
file_name = input("type the file name: ")
2
def read_txt(file_name):
3
file = open(file_name, "r")
4
lines = [x for i in file.readlines() for x in list(map(int, i.strip().split(',')))]
5
file.close()
6
return lines
7
print(read_txt(file_name))
8
Output:
JavaScript
1
2
1
[7, 1, 2, 3, 4, 3 2, 6, 1, 3, 1]
2