编程入门作业求助:如何用input获取文件名并结合open()函数
Hey Jordan, let's walk through how to adjust your code to meet that assignment requirement—this is such a common first step in file handling, so you’re already on the right track!
1. 用input()获取用户输入的文件名
The input() function prompts the user to enter text, then returns exactly what they type. You can store this in a variable (like filename) and pass that variable directly to open() instead of hardcoding a specific file name like 'testFile.docx'.
Quick example of how to use it:
filename = input("请输入要读取的文件名:")
2. 结合input()和open(),并优化文件处理
Your original code manually calls close() for files, which works—but Python has a safer, cleaner way with the with statement. It automatically closes the file for you once you’re done with it, so you don’t have to remember or worry about unclosed files if something goes wrong. Let’s cover both approaches, starting with what you’re already familiar with.
方式一:基于你现有代码的修改
We’ll swap out the hardcoded file name with the user’s input, then adjust the reading logic to only show the first 5 lines:
def main(): # Keep your test file writing code (if you need it for testing) outfile = open('testFile.docx', 'w') outfile.write('Hello World\n') outfile.write('It is raining outside\n') outfile.write('Ashley is sick\n') outfile.write('My dogs name is Bailey\n') outfile.write('My cats name is Remi\n') outfile.write('Spam Eggs and Spam\n') outfile.close() # Key change: Get filename from user input filename = input("请输入要读取的文件名:") # Open the file using the user-provided name infile = open(filename, 'r') # Read and print the first 5 lines print("文件的前5行内容:") for _ in range(5): line = infile.readline() # Stop early if the file has fewer than 5 lines if not line: break print(line, end='') # end='' avoids extra newlines (each line already has \n) infile.close() main()
方式二:用更安全的with语句(推荐)
This is the best practice in Python for file handling—no need to manually call close():
def main(): # Write test file with `with` (auto-closes when done) with open('testFile.docx', 'w') as outfile: outfile.write('Hello World\n') outfile.write('It is raining outside\n') outfile.write('Ashley is sick\n') outfile.write('My dogs name is Bailey\n') outfile.write('My cats name is Remi\n') outfile.write('Spam Eggs and Spam\n') # Get filename from user filename = input("请输入要读取的文件名:") # Read and print first 5 lines with `with` print("文件的前5行内容:") with open(filename, 'r') as infile: for _ in range(5): line = infile.readline() if not line: break print(line, end='') main()
3. 关键细节解释
input()returns a string, which is exactly whatopen()expects for its first argument.readline()grabs one line of the file at a time. We loop 5 times to get the first 5 lines, and stop early if we hit the end of the file (whenreadline()returns an empty string).- Using
withensures your file is always closed properly, even if an error happens while reading/writing.
With these changes, your program will let users input any filename, then display the first 5 lines of that file—perfect for your assignment!
内容的提问来源于stack exchange,提问作者Jordan Sweeney

