python - 在同一脚本中读取和写入

标签 python python-2.7

我目前正在进行艰难学习 Python 中的练习 16,我的代码在写入文件时遇到问题,但我的最终打印命令不打印内容将文件拖到控制台上。在我的命令行上,它只是出现了几行空格。据我了解,“r+”以读写模式打开它,但计算机无法读取它。 有人可以告诉我有什么问题吗?任何帮助将不胜感激:)

    from sys import argv
    script, file = argv

    print "The name of the file is %s" % file
    filename = open(file,"r+")

    print "First we must write something in it "
    print "Do you want to continue?Press CTRL-C if not."
    raw_input()

    print "Type the first line of the text"
    line1 = raw_input(">")+"\n"

    print "Type the second line of text"
    line2 = raw_input(">")+"\n"

    print "Type the third line of text"
    line3 = raw_input(">")+"\n"

    sum_line = line1 + line2 + line3

    print "Now I will write it to the file"
    filename.write(sum_line)

    print "The file now says:"

    #This line here does not print the contents of the file
    print filename.read()

    filename.close()

最佳答案

正如第一个答案中所包含的那样,写入后偏移量将指向文件末尾。但是,您不需要关闭该文件并重新打开它。最好在阅读之前执行此操作:

filename.seek(0)

这将重置文件开头的偏移量。

然后简单地阅读它。

 filename.read()    

关于python - 在同一脚本中读取和写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33839717/

相关文章:

Python:a,b=1,2 和 a=1;b=2 是否严格等价?

python - 如何在python中做if else语句

python - 如何找到一个很长的字符串的所有唯一子串?

python - 为什么 .strip() 不删除空格?

python - 如何使用 BeautifulSoup 登录亚马逊

python - 为什么 python3 不关心源文件中的非 ascii 字符?

python-2.7 - 导入错误:没有名为 eventlet 的模块

python - 如何在Python中向整数添加尾随零?或者如何在 python 中的任何整数后面添加零?

python - cx_Oracle.DatabaseError : DPI-1047: 64-bit Oracle Client library cannot be loaded: "dlopen(libclntsh.dylib, 1): image not found"

python - 将对象或对象数组发布到 API