0

I’m new to python and I’m taking my first steps to create some scripts. I want to access a file and store the items into a list and access each item as its own variable. The format of the file is .txt and it’s as such but not limited to 3 columns it could be 4 or more.

textData,1

textData,2

textData,3,moreData

textData,4,moreData4

textData,5 

I know how to read and append to a list and access individual items starting with [0] but when I do that I get textData, 1 for [0] and I only want textData on its own and 1 on its own and so on as I loop through the file.

Below is my start of this:

file = open('fileName','r')

list = []

for items in file:

  list.append(items)

print(list[0])

Thank you for taking the time to read and provide direction.

1
  • 1
    as an aside, don't use list as a variable name, it shadows the built-in list Commented Oct 23, 2017 at 16:52

2 Answers 2

1

You need to split the lines:

my_list = []
for lines in file:
    my_list.append(lines.split(','))

print(my_list)
Sign up to request clarification or add additional context in comments.

2 Comments

please don't use list as a variable.
You are right. I have just taken the authors variable names. I should have use more sensible ones and not one that shadows a datatype. I have corrected my code.
0

When you loop over a file object, you get each line as a str. You can then get each word by using the .split method, which returns a list of strs. As your items are comma-separated, we split on ','. We do not want to append this list to the overall list, but rather add all elements of the list to the overall list, hence the +=:

file = open('fileName', 'r')
mylist = []
for line in file:
    words = line.split(',')
    mylist += words
print(mylist[0])

Also, avoid using list as a variable name, as this is the name of the builtin list function.

3 Comments

thank you for the quick reply but I still get textData,1 and I just want TextData for [0] and 1 for [1]
This worked and thank you. Now I need to study what you did and understand it.
Indeed. If you are satisfied, please accept it as the answer. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.