Create a List that contain each Line of a File [duplicate]

I'm trying to open a file and create a list with each line read from the file.

   for Line in inFile:
   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?

Asked by: Alina911 | Posted: 28-01-2022

Answer 1

It's a lot easier than that:

List = open("filename.txt").readlines()

This returns a list of each line in the file.

Answered by: Ned509 | Posted: 01-03-2022

Answer 2

I did it this way

lines_list = open('file.txt').read().splitlines()

Every line comes with its end of line characters (\n\r); this way the characters are removed.

Answered by: Justin677 | Posted: 01-03-2022

Answer 3

my_list = [line.split(',') for line in open("filename.txt")]

Answered by: Emily665 | Posted: 01-03-2022

Answer 4

Please read PEP8. You're swaying pretty far from python conventions.

If you want a list of lists of each line split by comma, I'd do this:

l = []
for line in in_file:

You'll get a newline on each record. If you don't want that:

l = []
for line in in_file:

Answered by: Freddie807 | Posted: 01-03-2022

Answer 5

A file is almost a list of lines. You can trivially use it in a for loop.

myFile= open( "SomeFile.txt", "r" )
for x in myFile:
    print x

Or, if you want an actual list of lines, simply create a list from the file.

myFile= open( "SomeFile.txt", "r" )
myLines = list( myFile )
print len(myLines), myLines

You can't do someList[i] to put a new item at the end of a list. You must do someList.append(i).

Also, never start a simple variable name with an uppercase letter. List confuses folks who know Python.

Also, never use a built-in name as a variable. list is an existing data type, and using it as a variable confuses folks who know Python.

Answered by: Samantha892 | Posted: 01-03-2022

Answer 6

f.readlines() returns a list that contains each line as an item in the list

if you want eachline to be split(",") you can use list comprehensions

[ list.split(",") for line in file ]

Answered by: Nicole637 | Posted: 01-03-2022

Answer 7

Assuming you also want to strip whitespace at beginning and end of each line, you can map the string strip function to the list returned by readlines:

map(str.strip, open('filename').readlines())

Answered by: Arthur456 | Posted: 01-03-2022

Answer 8

... Also If you want to get rid of \n

In case the items on your list are with \n and you want to get rid of them:

with open('your_file.txt') as f:

Answered by: Daryl957 | Posted: 01-03-2022

Answer 9

I am not sure about Python but most languages have push/append function for arrays.

Answered by: Aida862 | Posted: 01-03-2022

Similar questions

python - Create a list from a long int

I've got a very long ( 1000 digit ) number. I want to convert it into a list , how would you go about it since : list(n) TypeError: 'long' object is not iterable

python - need to create a list from a text file

I need to return a list of pairs (,y,z), number of times it appears) in a text file with 1,000 entries. The function def eventfreq(year, month):takes the year and month of the previously mentioned as parameters. So far, I have defined year and month def eventfreq(year, month): F=fieldict('DOT1000.txt') for line in F: year=F[1].year month=F[1...

python - Create a 2D list out of 1D list

I am a bit new to Python and I want to convert a 1D list to a 2D list, given the width and length of this matrix. Say I have a list=[0,1,2,3] and I want to make a 2 by 2 matrix of this list. How can I get matrix [[0,1],[2,3]] width=2, length=2 out of the list?

Python create list from CSV

I am trying to build a python list from a CSV file. My CSV file has 5 columns as shown below separated by pipe(|): QTP|Install|C:\Cone_Automation\RunTest.vbs|Install|Sequence QTP|Open |C:\Cone_Automation\RunTest.vbs|Open |Sequence QTP|Install|C:\Cone_Automation\RunTest.vbs|Install|Parallel QTP|Install|C:\Cone_Automation\RunTest.vbs|Install|Parallel QTP|Install|C:\Cone_Automation\RunTest.vbs|Install|Para...

python - Create list from for loop

this is my code so far print("L = ",[4,10,4,2,9,5,4]) Startlist = [4,10,4,2,9,5,4] usrinput = int(input("Enter an element to search for in the list: ")) for i in [i for i,x in enumerate(Startlist) if x == usrinput]: print(i) I'm trying to however make a new list from the for loops printed numbers.This is the sample run i got by entering 4 L = [4, 10, 4, 2, 9, 5, 4] En...

python - How to create a list of list from a txt file

Closed. This question does not meet Stack Overflow guid...

python - Create new list if

Closed. This question needs details or clarity. It ...

python - Is it possible to create a list of "def"?

Closed. This question needs to be more focused. It ...

python - Create a list in a list from a file

I am trying to create a Python list in a list by reading a file. The file contain the lines: 12, 'MWSTRES1', 'K1317055', 1 15, 'MWSTRES1', 'K1416241', 3 13, 'MWSTRES1', 'K1316235', 8 9, 'BTBITSPQ', 'J03016235', 3 1, 'PLAUSP01', 'K1316235', 2 2, 'VTNTBMOT', 'K1316237', 9 4, 'VTNTBMOT', 'K1316239', 13 Code: combs = [] with open('file3', 'r') as f: result...

python - Create list out of set

I am reading Dive into Python3 book and following examples. In chapter 2 , Native Datatypes I am trying , like in example to create list out of set. a_list = ['a', 'b', 'mpilgrim', True, False, 42] a_set = set(a_list) a_set But I am getting TypeError: Traceback (most recent call last): File "<stdin>",...

python - Can't create a list from a set

What am I doing wrong: (Pdb) aaa = set(list1).intersection(list2) (Pdb) list(aaa) *** Error in argument: '(aaa)' (Pdb) type(aaa) <type 'set'> This code should work, shouldn't it?

python create list within while loop

I have defined a function to read lines from a file into a list. I then want to call this function from within a while loop. The list is created correctly on the first loop, but the following loops create an empty list. How can I get my code to regenerate the list each time? (For clarification, this is not the final function, but I have isolated the issue in my code to the generation of the list).

python - How to create a new list for each line in a file?

I am trying to create a soduko styled program. A notepad/word document is uploaded into Python and I want Python to check: Each line (row) has the same number of characters Each column has the same number of characters No characters are repeated twice in either a column or in a row Every character is used once and only once per column and per row The file uploaded can either be a numerical soduko or an alph...

python - Create a set from a list using {}

Sometimes I have a list and I want to do some set actions with it. What I do is to write things like: >>> mylist = [1,2,3] >>> myset = set(mylist) {1, 2, 3} Today I discovered that from Python 2.7 you can also define a set by directly saying {1,2,3}, and it appears to be an equivalent way to define it. Then, I wondered if I can use this syntax to crea...

python - How can i create a list with this API Data?

I'm using the runescape API for high scores. I am getting back all of my stats from the api which is fine but im trying to figure out how choose to a specific number and print this number.. for example the number (2422) import urllib3 from bs4 import BeautifulSoup import requests url = ("") r = requests.get(url) soup = Beautif...

python - How to create a 1d list with a .txt that has \n?

I want to read in a a text file and put every element of the file into one list instead of having a separate list for every line in the file. So for example, if the file was: Hello my name Is Joe I want the list to be [Hello my name Is Joe] instead of [[Hello my name] [is Joe]] Here's what I have so far def evaluate_essay(): fileList= [] file= open("...

python - How do I create a list like the one below?

I have a series on URL's that I need to replicate as follows.*1205* The 1205 is variable the final outputs need to look like "" ................................................#taxpage2" ................................................#taxpage3 .................................

python - Create a list from file and find max value

file = open('data.txt') data = [] h = [i[:-1] for i in file] def maximum_cols(list): for line in h: data.append(line) y = [int(n) for n in data] x = None for value in data: value = int(value) if not x: x = value elif value > x: x = value return x maximum_cols(data) print(data) So I'm trying to read a file into 2...

python - Create a new list according to item value

I have a list like below. ['T46', 'T43', 'R45', 'R44', 'B46', 'B43', 'L45', 'L44', 'C46', 'C45'] where I want to group according to int value: [id][' ',' ',' ',' ',' '] # AREA PATTERN [Top, Right, Bottom, Left, Center] [46]['1','0','1','0','1'] #Top,Bottom,Center [45]['0','1','0','1','1'] #Right,Left,Center [43]['1','0','1','0','0'] #Top,Bottom [44]...

python - Create a list for each item in another list

How can I create an empty list for each item on another list (variable in length). where the to be created list name contains the item value. i.e. ['NSW', 'ACT', 'VIC'] newly created lists NSW_list[] ACT_list[] VIC_list[]

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - Any way to create a NumPy matrix with C API?

I read the documentation on NumPy C API I could find, but still wasn't able to find out whether there is a possibility to construct a matrix object with C API — not a two-dimensional array. The function is intended for work with math matrices, and I don't want strange results if the user calls matrix multiplication forgetting to convert this value from an array to a matrix (multiplication and exponentiation being the only ...

python - How can i create a lookup in Django?

I have a Question model & Form, one of the fields in this model is userid=ForeignKey(User), this Works perfectly well on the Question Model, am able to pick the user from a drop down. But kind a tricky when i want to list the question from the model, which is the best way to lookup the user name from the Users table? becouse at this point i cant have the dropdown! I wa...

python - create an array from a txt file

I'm new in python and I have a problem. I have some measured data saved in a txt file. the data is separated with tabs, it has this structure: 0 0 -11.007001 -14.222319 2.336769 i have always 32 datapoints per simulation (0,1,2,...,31) and i have 300 simulations (0,1,2...,299), so the data is sorted at first with the number of simulation and then the number of the data point.

python - Create numpy matrix filled with NaNs

I have the following code: r = numpy.zeros(shape = (width, height, 9)) It creates a width x height x 9 matrix filled with zeros. Instead, I'd like to know if there's a function or way to initialize them instead to NaNs in an easy way.

python - How can I create 1000 files that I can use to test a script?

I would like to create 1000+ text files with some text to test a script, how to create this much if text files at a go using shell script or Perl. Please could anyone help me?

python - How to create a custom django filter tag

I am having trouble in getting my site to recognise custom template tags. I have the following dir structure: project_name project_name templatetags _ __init __ views _ __init __ index.html views

python - how does create a new app in pinax?

thanks only need 'python startapp xx' ???

python - Should I create each class in its own .py file?

I'm quite new to Python in general. I'm aware that I can create multiple classes in the same .py file, but I'm wondering if I should create each class in its own .py file. In C# for instance, I would have a class that handles all Database interactions. Then another class that had the business rules. Is this the case in Python?

python - how to create a theme with QT

im looking for a way to make my pyqt interface look nicer by adding a theme to it. im new to Qt and i still have no idea how to add a custom theme for widgets.. so how is that possible ? and is it possible through qt designer ? sorry for my bad english , its my third language. i hope the idea is clear enough . please let me know if something was unclear .. thanks in advace

python - What's the best Django search app?

How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.

python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.

python - What is the best way to copy a list?

This question already has answers here:

python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?

python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python