I want to read the file line by line and save it to the array

Asked 2 years ago, Updated 2 years ago, 99 views

It's exactly what it says. File is

hello C world! hello python world!

If I say I have it like this a[0] = 'hello C world!' a[1] = 'hello python world!' I want to make it come out like thisYo

string file python

2022-09-22 22:35

1 Answers

I'll tell you four ways.

fname = "file path"

#1.
with open(fname) as f:
    lines = f.readlines()

#2.
lines = [line.rstrip('\n') for line in open(fname)]

#3.
with open(fname, "r") as ins:
    lines = []
    for line in ins:
        array.append(line)
#4.
lines = tuple(open(fname, 'r'))


2022-09-22 22:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.