Consider this scenario (which I ran into in real life):
I want to open a text file and do a lot of processing on the lines
of that file.
If the file does not exist I want to take appropriate action, e.g.
print an error message and abort the program.
I might write it like this:
try:
On 2024-07-06 at 11:49:06 +0100,
Rob Cliffe via Python-list wrote:
> Is there a better / more Pythonic solution?
https://docs.python.org/3/library/fileinput.html
At least this attempts to abstract the problem of iterating over a file
(or multiple files) into a library routine. I've used it a l
On 06/07/2024 11:49, Rob Cliffe via Python-list wrote:
> If the file does not exist I want to take appropriate action, e.g.
> print an error message and abort the program.
> I might write it like this:
>
> try:
> with open(FileName) as f:
> for ln in f:
> print("I
On Sat, 6 Jul 2024 at 11:55, Rob Cliffe via Python-list
wrote:
>
> Consider this scenario (which I ran into in real life):
> I want to open a text file and do a lot of processing on the lines
> of that file.
> If the file does not exist I want to take appropriate action, e.g.
> print an
On 7/6/2024 6:49 AM, Rob Cliffe via Python-list wrote:
Consider this scenario (which I ran into in real life):
I want to open a text file and do a lot of processing on the lines
of that file.
If the file does not exist I want to take appropriate action, e.g.
print an error message and
My thoughts is that if the "many lines of code" puts the except to far
from the try, then perhaps it would have made sense to factor out some
part there into a function.
Perhaps like:
try:
with open(FileName) as f:
for ln in f{
process(ln)
except FileNotFoundError:
print(f"F
On 6/07/24 22:49, Rob Cliffe via Python-list wrote:
Consider this scenario (which I ran into in real life):
I want to open a text file and do a lot of processing on the lines
of that file.
If the file does not exist I want to take appropriate action, e.g.
print an error message and ab
On 06Jul2024 11:49, Rob Cliffe wrote:
try:
f = open(FileName) as f:
FileLines = f.readlines()
except FileNotFoundError:
print(f"File {FileName} not found")
sys.exit()
# I forgot to put "f.close()" here -:)
for ln in File Lines:
print("I do a lot of processing here")