Python allows putting multiple open() statements in a single with. You comma-separate them. Your code would then be:

def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

# input the name you want to check against
text = input('Please enter the name of a great person: ')    
letsgo = filter(text,'Spanish', 'Spanish2')

And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)

Using multiple open() items with with was not supported in Python 2.5 when the with statement was introduced, or in Python 2.6, but it is supported in Python 2.7 and Python 3.1 or newer.

http://docs.python.org/reference/compound_stmts.html#the-with-statement http://docs.python.org/release/3.1/reference/compound_stmts.html#the-with-statement

If you are writing code that must run in Python 2.5, 2.6 or 3.0, nest the with statements as the other answers suggested or use contextlib.nested.

Answer from steveha on Stack Overflow
🌐
W3Schools
w3schools.com › PYTHON › python_file_open.asp
Python File Open
Python Examples Python Compiler ... demofile.txt This file is for testing purposes. Good Luck! To open the file, use the built-in open() function....
🌐
freeCodeCamp
freecodecamp.org › news › with-open-in-python-with-statement-syntax-example
With Open in Python – With Statement Syntax Example
July 12, 2022 - To use the open function, you declare a variable for it first. The open() function takes up to 3 parameters – the filename, the mode, and the encoding. You can then specify what you want to do with the file in a print function.
Discussions

with open vs open in python
Here with is a context manager that ensures your resources are closed when you’re done for whatever reason. Without it, you need to pair open with close (and might worry somewhat about what happens if exceptions get thrown, etc. that prevent that close from being reached). In general using with is good practice, but usually beginners get subjected to open and close initially. More on reddit.com
🌐 r/learnpython
57
158
May 19, 2021
How do I open a file from my laptop with python?
You need to prefix your string with r to tell python its a raw string and not to attempt to parse special characters like \U # ...........\/ reader = open(r"C:\Users\ADMIN\Downloads\cat.png","r") More on reddit.com
🌐 r/learnpython
26
23
December 30, 2023
How to open files?
Put quotes around the file name. Also use context managers: with open(‘dna.txt’, ‘r’) as my_file: # do stuff More on reddit.com
🌐 r/learnpython
12
1
October 4, 2018
Total noob with ROS, need to open a .bag file and extract info, how?
The official way to get the information, is to use it in ROS and play that file: https://www.youtube.com/watch?v=Vlp0e89TXpI More on reddit.com
🌐 r/ROS
13
4
January 6, 2022
Top answer
1 of 5
402

Python allows putting multiple open() statements in a single with. You comma-separate them. Your code would then be:

def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

# input the name you want to check against
text = input('Please enter the name of a great person: ')    
letsgo = filter(text,'Spanish', 'Spanish2')

And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)

Using multiple open() items with with was not supported in Python 2.5 when the with statement was introduced, or in Python 2.6, but it is supported in Python 2.7 and Python 3.1 or newer.

http://docs.python.org/reference/compound_stmts.html#the-with-statement http://docs.python.org/release/3.1/reference/compound_stmts.html#the-with-statement

If you are writing code that must run in Python 2.5, 2.6 or 3.0, nest the with statements as the other answers suggested or use contextlib.nested.

2 of 5
40

Use nested blocks like this,

with open(newfile, 'w') as outfile:
    with open(oldfile, 'r', encoding='utf-8') as infile:
        # your logic goes right here
🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.6 documentation
More information can be found in the printf-style String Formatting section. open() returns a file object, and is most commonly used with two positional arguments and one keyword argument: open(filename, mode, encoding=None)
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › open-a-file-in-python
Open a File in Python - GeeksforGeeks
July 12, 2025 - We can also use open() function and with keyword to open a file in Python.
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-file.html
File Read Write
Conclusion: 3 lines of Python, can just have a list of all the words, ready for a loop or whatever. Another technique, the call f.readlines() returns a list of strings, one for each line. Sometimes it's more useful to have all the lines at once, vs. getting them one at a time in the standard loop. Can access the lines in any order, or use a slice to get rid of some, and so on. with open(filename) as f: lines = f.readlines() # lines[0], lines[1], ..
🌐
Python
docs.python.org › 3 › library › filesys.html
File and Directory Access — Python 3.14.6 documentation
Operating system interfaces, including functions to work with files at a lower level than Python file objects. ... Python’s built-in I/O library, including both abstract classes and some concrete classes such as file I/O. ... The standard way to open files for reading and writing with Python.
🌐
Reddit
reddit.com › r/learnpython › how do i open a file from my laptop with python?
r/learnpython on Reddit: How do I open a file from my laptop with python?
December 30, 2023 -

I was learning how to read and write external files in python but the tutorial covered only about the files that are already located inside the same folder of an IDE.

Googling and reading articles took me nowhere so here I am.

reader = open("C:\Users\ADMIN\Downloads\cat.png","r")
print(reader.readable())

And this is the error it's throwing at me ->

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I would really appreciate if someone could please explain the error and the process for reading a file saved in my device with python.

🌐
Note.nkmk.me
note.nkmk.me › home › python
Read, Write, and Create Files in Python (with and open()) | note.nkmk.me
May 7, 2023 - In Python, the open() function allows you to read a file as a string or list, and create, overwrite, or append a file. Read and write files with open() and withEncoding specification: encoding Encodin ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-read-from-a-file-in-python
Reading a File in Python - GeeksforGeeks
Reading from a file in Python means accessing and retrieving contents of a file, whether it be text, binary data or formats like CSV and JSON. It is widely used in real-world applications such as reading configuration files, processing logs or handling datasets in data science. ... Basic file reading involves opening a file, reading its contents, and closing it properly to free up system resources.
Published   September 5, 2025
🌐
Medium
medium.com › codex › how-to-open-view-files-in-python-e77e3e9d3f1d
How to open/read files in Python. When I first started practicing coding… | by Sid Ghani | CodeX | Medium
December 19, 2024 - With our file path set to a variable named “Path”, we are ready to move on · We now want to use the Open function to open our text file. To do that we need to assign a new variable we will call File and write the following code: In the ...
🌐
Reddit
reddit.com › r/learnpython › how to open files?
r/learnpython on Reddit: How to open files?
October 4, 2018 -

I'm an extreme noobie working on opening up files in Python. I'm writing the following code:

my_file = open("dna.txt")

It's returning the following error:

Traceback (most recent call last):

File "<pyshell#3>", line 1, in <module>

my_file = open("dna.txt")

FileNotFoundError: [Errno 2] No such file or directory: 'dna.txt'

I have a text file called dna.txt but I don't know how to further 'define' it. Any ideas?

🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-open-a-file-using-the-with-statement
How to open a file using the with statement - GeeksforGeeks
July 23, 2025 - While using open() we need to explicitly close an opened file instance, else other parts of code may face errors while opening the same file. In with open() the closing of the file is handled by the context manager.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-read-file-open-write-delete-copy
Python open() Function Explained: How to Open, Read, and Write Files | DigitalOcean
June 25, 2025 - By the end of this tutorial, you’ll ... tasks in your projects. ... The with open() statement is the standard and safest method for handling files because it automatically closes the file for you, even if your code runs into an error....
🌐
Medium
medium.com › @noransaber685 › understanding-file-handling-in-python-open-read-write-append-json-serialization-and-more-b041f861d9fb
Understanding File Handling in Python: Open, Read, Write, Append, JSON Serialization, and More | by Noran Saber Abdelfattah | Medium
February 3, 2024 - Python will read or write the contents of the file as strings when you open it in text mode. Text can, however, be represented using a variety of character encodings, including Latin-1, ASCII, and UTF-8. You can define the character encoding ...
🌐
Medium
medium.com › @kollisnehagowri › file-modes-in-python-b0ec2e3c89aa
File Modes In Python. In Python, the ‘open()’ function… | by Sneha Gowri Kolli | Medium
May 16, 2023 - Example: file = open(‘file.txt’, ‘w+’) file.write(“This line is added in write and read mode.”) content = file.read() file.close() These are some of the commonly used file modes in Python. Remember to close the file using the `close()` method when you’re done working with it to free up system resources.
🌐
Compciv
compciv.org › guides › python › fileio › open-and-read-text-files
Opening files and reading from files | Computational Methods in the Civic Sphere at Stanford University
Pretend you have a file named example.txt in the current directory. If you don't, just create one, and then fill it with these lines and save it: ... Here's a short snippet of Python code to open that file and print out its contents to screen – note that this Python code has to be run in the same directory that the example.txt file exists in.
🌐
Codecademy
codecademy.com › article › handling-text-files-in-python
Handling Text Files in Python: How to Read from a File | Codecademy
The open() function is a built-in function in Python that is essential for file access and manipulation. It allows us to read, write, and append data to a file, making it the first step in interacting with external files in Python.