Python初学者,在文件部分遇到的基础
"""
File: files.py
The solutions for these programs are provided, to help you get going - or to confirm that your solution was
valid.
Note: when you execute a Python program that contains a line like open('data.txt', 'w') the new file
“data.txt” is created in the same folder as the Python file in your PyCharm project.
Create a new file called files.py and do all the following separate questions in it:
Note: the intention is to give you experience using different ways to read files.
Make sure you’re confident with:
• read()
• readline()
• readlines()
• for line in file
1. Write code that asks the user for their name, then opens a file called “name.txt” and writes that name
to it.
2. Write code that opens “name.txt” and reads the name (as above) then prints,
“Your name is Bob” (or whatever the name is in the file).
3. Create a text file called numbers.txt and save it in your prac_02 directory. Put the following three
numbers on separate lines in the file and save it:
17
42
400
Write code that opens “numbers.txt”, reads only the first two numbers and adds them together then
prints the result, which should be. . . 59.
4. Now write a fourth block of code that prints the total for all lines in numbers.txt or a file with any
number of numbers.
"""
我在文件这部分学的有点迷,今天再看的时候遇到这个问题,写不下来,麻烦看一下,给个完整代码,要是有详细一些注释就太感谢了