gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
how to use with .. as to open two files in python?
- User
how to use with .. as to open two files in python?
- Assistant
You can use the
withstatement to open two files in Python like this:with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2: # Do something with file1 and file2Here, we're opening two files (file1.txt and file2.txt) for reading using the
open()function and the'r'mode. We're also using thewithstatement, which automatically closes the files when we're done with them.Inside the
withblock, we can accessfile1andfile2as file objects and perform operations on them. Once the block is exited, Python automatically closes both files.