I usually do something like that:
f = open("data.txt", "r") data = f.read().splitlines() f.close() for line in data: print(line)
And then I can work with data
.
However very often I see people doing it like that:
with open("data.txt", "r") as f: for line in f: print(line)
Do you not need to close the file when using with
? Also I noticed I get into problems when using .splitlines()
or .pop()
with second method, maybe because I use those on f
and in first method I assign f
to data
first. Somehow first way seems less prone to errors, but maybe that’s because I’ve used it before.
submitted by /u/CMDR_Pumpkin_Muffin
[link] [comments]
r/learnpython I usually do something like that: f = open(“data.txt”, “r”) data = f.read().splitlines() f.close() for line in data: print(line) And then I can work with data. However very often I see people doing it like that: with open(“data.txt”, “r”) as f: for line in f: print(line) Do you not need to close the file when using with? Also I noticed I get into problems when using .splitlines() or .pop() with second method, maybe because I use those on f and in first method I assign f to data first. Somehow first way seems less prone to errors, but maybe that’s because I’ve used it before. submitted by /u/CMDR_Pumpkin_Muffin [link] [comments]
I usually do something like that:
f = open("data.txt", "r") data = f.read().splitlines() f.close() for line in data: print(line)
And then I can work with data
.
However very often I see people doing it like that:
with open("data.txt", "r") as f: for line in f: print(line)
Do you not need to close the file when using with
? Also I noticed I get into problems when using .splitlines()
or .pop()
with second method, maybe because I use those on f
and in first method I assign f
to data
first. Somehow first way seems less prone to errors, but maybe that’s because I’ve used it before.
submitted by /u/CMDR_Pumpkin_Muffin
[link] [comments]