Daymnn
Daymnn

Reputation: 229

Putting items into array

I'm working on a Python project in Visual Studio. I want to process a longer text file, this is a simplified version:

David Tubb
Eduardo Cordero
Sumeeth Chandrashekar

So for reading this file I use this code:

with open("data.txt", "r") as f:
    f_contents = f.read()
    print(f_contents)

I want to put these items into a new array that looks like that:

['David Tubb','Eduardo Cordero','Sumeeth Chandrashekar']

Is that possible?

Upvotes: 1

Views: 68

Answers (3)

Colonel_Old
Colonel_Old

Reputation: 932

Yes, the following code will work for this:

output = [] # the output list
nameFile = open('data.txt', 'r') 

for name in nameFile:
    # get rid of new line character and add it to your list
    output.append(name.rstrip('\n'))

print output

# don't forget to close the file!
nameFile.close()

Upvotes: 3

Srce Cde
Srce Cde

Reputation: 1824

result = []
with open("data.txt", "r") as f:
    result = f.read().splitlines()
print(result)

Output:

['David Tubb', 'Eduardo Cordero', 'Sumeeth Chandrashekar']

Upvotes: 1

Jimmy Newsom
Jimmy Newsom

Reputation: 66

The method stated by python for opening a file context is using "with open", this ensures the context will end during clean up.

python.org-pep-0343

dalist = list()
with open('data.txt', 'r') as infile:
    for line in infile.readlines():
        dalist.append(line)

Additonal resource for contex handeling: https://docs.python.org/3/library/contextlib.html

Upvotes: 0

Related Questions