Python3新手求助:下载临时文件后遇FileNotFoundError路径报错
Hey there! Let's walk through the problems in your code and get it working properly. I've spotted several key issues causing your errors, so let's tackle them one by one:
1. The Immediate FileNotFoundError Cause
The first critical mistake is how you're opening your file:
file_out = open("path_file" , "r")
You're using the string literal "path_file" instead of the variable path_file. Python is trying to find a file literally named "path_file" in your working directory (which doesn't exist) instead of using the path stored in your variable. Fix this by removing the quotes:
file_out = open(path_file , "r")
2. Wasting the Downloaded Temporary File Path
You're hardcoding a file path (path_file =r'C:/Users/...') instead of using the actual temporary path returned by urlretrieve. The gt_url variable holds the path to your downloaded file as its first element (gt_url[0]), so you should use that instead of a hardcoded value—this ensures you're working with the exact file you downloaded, not a random path you guessed.
3. Broken File Manipulation Logic
Your file handling code has multiple flaws that will cause errors even after fixing the path issue:
- You call
open("file_back", "w")but don't assign the returned file object tofile_back, so subsequent calls likefile_back.write()will throw an attribute error. - You can't directly write a file object (
file_back.write(file_out)); you need to write the content of the file, not the object itself. - Using
readlines()moves the file pointer to the end of the file, so inserting content requires careful handling of the file position (or better yet, manipulating content in memory first). - You're opening files without always assigning them to variables, leading to broken references.
Corrected Code
Here's a revised version of your code that fixes all these issues, with comments explaining the changes:
import urllib.request # Download the URL and get the temporary file path url = 'http://pages.di.unipi.it/corradini/Didattica/AP-17/PROG-ASS/03/assignment3.html' gt_url = urllib.request.urlretrieve(url) downloaded_file_path = gt_url[0] # Grab the actual path of the downloaded temp file print("Downloaded file path:", downloaded_file_path) # Read content from the downloaded file (using 'with' to auto-close files) with open(downloaded_file_path, 'r', encoding='utf-8') as downloaded_file: downloaded_content = downloaded_file.readlines() # Read your Java snippet with open("snip1.java", 'r', encoding='utf-8') as java_file: java_snippet = java_file.readlines() # Insert the Java snippet into the downloaded content (adjust the index to your desired position) # Example: Insert after the 10th line of the HTML file insert_position = 10 modified_content = downloaded_content[:insert_position] + java_snippet + downloaded_content[insert_position:] # Write the modified content to a new output file with open("file_back.html", 'w', encoding='utf-8') as output_file: output_file.writelines(modified_content) # Verify the result print("\nModified content preview:") with open("file_back.html", 'r', encoding='utf-8') as result_file: print(result_file.read())
Key Improvements:
- Uses
withstatements for file handling: This automatically closes files for you, preventing resource leaks and messyclose()calls. - Properly leverages the temporary path from
urlretrieveinstead of hardcoding. - Manipulates content in memory first: This is a cleaner, more reliable approach than trying to edit files in-place.
- Adds
encoding='utf-8'to avoid character encoding issues with HTML content. - Breaks the process into clear, readable steps: download → read → modify → write.
If you need to insert the Java snippet at a specific logical point (not just a line number), you can add logic to search for a specific string in the HTML (like a comment or tag) and insert the snippet after that line.
内容的提问来源于stack exchange,提问作者saharsa

