Make a file that prompts the use for a filename, Create Python Read File
时间: 2024-02-01 19:02:37 浏览: 88
Sure, here's an example code snippet for creating a Python script that prompts the user for a filename and then reads the contents of the file:
```python
# Prompt user for filename
filename = input("Enter the name of the file to read: ")
# Open file for reading
try:
with open(filename, 'r') as f:
# Read contents of file
file_contents = f.read()
# Print contents of file
print(file_contents)
except FileNotFoundError:
print(f"File '{filename}' not found.")
```
In this script, the `input()` function is used to prompt the user for the filename. Then, the `open()` function is used to open the file for reading. If the file is found, its contents are read using the `read()` method and printed to the console. If the file is not found, an error message is printed. You can modify this code to suit your needs, such as parsing the contents of the file or performing some other action on it.
阅读全文