Getting exception details in Python

前端 未结 4 829
故里飘歌
故里飘歌 2021-02-04 00:04

I have to open & write to about 10 different files all within the same loop. e.g:

for i in range(0,10):
    try:
        a=5
        file1 = open(\"file1.txt         


        
4条回答
  •  暖寄归人
    2021-02-04 00:42

    You mention using a loop, but you're not actually using a loop. Use a loop. That way you can write each file, one at a time, inside a single try block. You don't appear to be doing anything with the files except write one value to each, so you don't need to keep them all open.

    for filename in ['file1.txt', 'file2.txt', ...]:
        try:
            with open(filename, 'w+') as f:
                f.write(str(a)+"whatever")
        except IOError:
            print("Error occurred with", filename)
    

    Edit: If you have wildly different things to write to the different files, create a dictionary or other data structure ahead of time storing the mapping between files and data, then use that in the loop.

    data = {'file1.txt': str(a), 'file2.txt': 'something else', 'file3.txt': str(a)+str(b)}
    
    for filename, output in data.items():
        try:
            with open(filename, 'w+') as f:
                f.write(output)
        except IOError:
            print("Error occurred with", filename)
    

提交回复
热议问题