I'm trying to open a file and create a list with each line read from the file.
i=0
list=[""]
for data in file_name:
list[i]=data.split(",")
i+=1
print list
But this sample code gives me an error because of the i+=1 saying that index is out of range. What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?
Tehran Noorani
19-Jun-2023Make sure to replace "path/to/your/file.txt" with the actual file path on your system. This code will open the file, iterate over each line, strip any leading or trailing whitespace, and append the line to the lines list. Finally, it will print each line in the list.
Aryan Kumar
19-Jun-2023Sure, here is how you can create a list that contains each line of a file in Python:
Python
This code first defines a function called
create_list_of_lines()
. The function takes a filename as input and returns a list of the lines in the file. The function works by first opening the file in read mode. Then, the function reads the lines of the file and stores them in a list. Finally, the function returns the list.The code then defines a variable called
filename
and assigns it the value of the file to read. The code then calls thecreate_list_of_lines()
function and stores the result in a variable calledlines
. Finally, the code iterates through the list of lines and prints each line to the console.To run the code, you can save it as a Python file and then run it from the command line. For example, if you save the code as
create_list_of_lines.py
, you can run it by typing the following command into the command line:Code snippet
This will print the lines of the file to the console.