• 技术文章 >常见问题 >Python常见问题

    python文件怎么保存

    silencementsilencement2019-12-04 13:18:04原创3379

    本文总结python保存文件的方法,需要的小伙伴可以学习一下。

    读文件

    1

    2

    3

    4

    5

    6

    7

    8

    f = open('Test.txt') #打开文件

    data = f.read() #读取文件

    print(data)

    # oneLine = f.readline()

    # print oneLine #读取第一行

    # lines = f.readlines() #把内容按行读取至一个list

    # print lines

    f.close() #关闭

    写文件

    1

    2

    3

    4

    5

    6

    f = open('output.txt','w') #output.txt - 文件名称及格式 w - writing

        #以这种模式打开文件,原来文件内容会被新写入的内容覆盖,如文件不存在会自动创建

    f.write("I'm going to write a string")

    out = open('output.txt','w')

    out.write("I'm Fine \nNow is raining!")

    out.close()

    从控制台输入并保存文件

    1

    2

    3

    4

    5

    6

    out = open('out.txt','w')while True:

        data = input('Please Input something(Enter q quit): ')

        if data != 'q':

            out.write(data + '\n')

        else:

            break

    从一个文件读取写入到另一个文件中

    1

    2

    3

    4

    5

    6

    newFile = open('output.txt')

    data = newFile.read()

    out = open('out.txt','w')

    out.write(data)

    newFile.close()

    out.close()

    专题推荐:文件
    上一篇:python怎么在cmd运行文件夹 下一篇:python输入用空格吗

    相关文章推荐

    • python文件后缀是什么

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网