plapapyjh 2022-09-04 14:42 采纳率: 43.5%
浏览 51
已结题

Python初学者,在文件部分遇到的基础问题

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.
"""

我在文件这部分学的有点迷,今天再看的时候遇到这个问题,写不下来,麻烦看一下,给个完整代码,要是有详细一些注释就太感谢了

img

  • 写回答

1条回答 默认 最新

  • EdsionWang 2022-09-04 15:12
    关注
    
    #将用户输入存到变量中
    name = input('what is your name:')
    #打开一个文件,将变量写入文件
    with open('name.txt', mode='w', encoding='utf-8') as file_obj:
        file_obj.write(name)
    
    
    
    #打开文件,后面的r是只读
    f = open('name.txt', 'r')
    #将文件中的行读出来放到变量中
    namefromfile = f.readline()
    #输出变量内容
    print('Your name is ' + namefromfile)
    #没有使用with语句块,则需要手动关闭文件
    f.close()
    
    
    
    f = open('numbers.txt', 'r')
    #把所有行读取出来
    lines = f.readlines()
    #第一行第二行装换成整数
    one = int(lines[0])
    two = int(lines[1])
    print('sum of first two lines:')
    #输出两个数的和
    print(one+two)
    f.close()
    
    
    
    f = open('numbers.txt', 'r')
    total = 0
    #for循环遍历所有行,并求和
    for line in f:
        total += int(line)
    print('total of all lines:')
    print(total)
    f.close()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月12日
  • 已采纳回答 9月4日
  • 修改了问题 9月4日
  • 赞助了问题酬金10元 9月4日
  • 展开全部

悬赏问题

  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。