zoukankan      html  css  js  c++  java
  • 文件操作

    首先,我们通过指明我们希望打开的文件和模式来创建一个file类的实例。模式可以为读模式('r')、写模式('w')或追加模式('a')。事实上还有多得多的模式可以使用,你可以使用help(file)来了解它们的详情。

    我们首先用写模式打开文件,然后使用file类的write方法来写文件,最后我们用close关闭这个文件。

    接下来,我们再一次打开同一个文件来读文件。如果我们没有指定模式,读模式会作为默认的模式。在一个循环中,我们使用readline方法读文件的每一行。这个方法返回包括行末换行符的一个完整行。所以,当一个 空的 字符串被返回的时候,即表示文件末已经到达了,于是我们停止循环。

    注意,因为从文件读到的内容已经以换行符结尾,所以我们在print语句上使用逗号来消除自动换行。最后,我们用close关闭这个文件。

    现在,来看一下poem.txt文件的内容来验证程序确实工作正常了。

    #!/usr/bin/python
    # Filename: using_file.py


    poem = '''
    Programming is fun
    When the work is done
    if you wanna make your work also fun:
            use Python!
    '''


    f = file('poem.txt''w'# open for 'w'riting
    f.write(poem) # write text to file
    f.close() # close the file

    f = file('poem.txt')
    # if no mode is specified, 'r'ead mode is assumed by default
    while True:
        line = f.readline()

        if len(line) == 0# Zero length indicates EOF
            break
        print line,
        # Notice comma to avoid automatic newline added by Python
    f.close() # close the file

  • 相关阅读:
    luogu1525 [NOIp2011]关押罪犯 (并查集)
    luogu1084 [NOIp2012]疫情控制 (二分答案+倍增+dfs序)
    luogu1083 [NOIp2012]借教室 (二分答案+差分)
    bzoj4152 The Captain (dijkstra)
    luogu1081 [NOIp2012]开车旅行 (STL::multiset+倍增)
    suoi22 WRX知识树(dfs序)
    [HNOI2010]弹飞绵羊
    1596: [Usaco2008 Jan]电话网络
    [Tyvj Jan]青蛙跳荷叶
    [BZOJ1116] CLO
  • 原文地址:https://www.cnblogs.com/nku-wangfeng/p/7690013.html
Copyright © 2011-2022 走看看