-3

I would like to save a file.txt line by line in variable (array or list) .So if the file.txt is:

hi there

what's up

I want my code to save it line by line in the same variable making a table so I can access easily each line when I want using that variable. And what can I do if I wanna access only line 2? It is supposed I don't know how many lines the file.txt has. Thank you very much!

Ginés Díaz
  • 117
  • 1
  • 10
  • 2
    So sit back take a cup of coffee and let us create your software. Good luck with that :-) Please provide us with code samples of what you tried until now. That way we can help you more effectively. – Ivonet Dec 13 '17 at 19:58
  • So read it line by line and save each line as a list in a nested list? What have you tried? – roganjosh Dec 13 '17 at 19:58
  • @Ivonet thank you! but is my first day with python and unless I tried I had no idea of what I did. I'll keep your advise :) – Ginés Díaz Dec 13 '17 at 20:22
  • @roganjosh I have the solution below, thank you very much! – Ginés Díaz Dec 13 '17 at 20:22

1 Answers1

0

Well it is super easy in Python:

text_file = open("filename.txt", "r")

# Splits the element by "\n"
lines = text_file.readlines()
text_file.close()

#Print List of Lines in your File
print(lines)

#Print Number of Lines in your File
print(len(lines))

#Access Second Line in your file
print(lines[1])# Since python is zero indexed
CodeCollector
  • 468
  • 2
  • 13