【问题标题】:learning Python the hard way argv and file艰难地学习 Python argv 和 file
【发布时间】:2016-08-23 06:48:49
【问题描述】:

过去几周我正在学习 python

from sys import argv
script,filename = argv 
print "We're delete the file %r" %filename
print "If you want to stop ctrl+c (^c)"
print "Please hit enter to continue"
raw_input(">_")
print "Opening file..."
filen = open(filename,'w')
print "Truncating your file...."
filen.truncate()
print "now in your file %r" %filen
print "Writing time write  something to your file"

line = raw_input("?")
print "write in progress..."
filen.write(line)
filen.write("\n end of document\n")
filen.close()

我想查看文件的内容,但是当我使用print filenameprint filen 时,它会显示名称并在变量filen 上打开文件

【问题讨论】:

  • 美元符号是怎么回事?

标签: python file argv filehandle


【解决方案1】:

您可以使用filen.read()filen.readline()filen.readlines()读取数据

1) 阅读

fo = open(filename,read)
fo.seek(0, 0) #seek is used to change the file position.This requires only for read method
fo.read(10) #This reads 1st 10 characters
fo.close()

2) 读取行

fo = open(filename,read)
fo.readline() #This will read a single line from the file. You can add for loop to iterate all the data
fo.close()

3) 阅读线。

fo = open(filename,read)
fo.readline() #read all the lines of a file in a list 
fo.close()

下面的文档会给你更好的主意。 https://docs.python.org/2/tutorial/inputoutput.html

【讨论】:

  • 如果你先写,你会想在阅读之前.seek(0)
  • 我添加了 "$print filen.read()" 我得到了 IOError: File not open for reading 所以我添加了 "$open(filen,'r') " 但这次我得到了 >> open(filen,'r') TypeError: coercing to Unicode: need string or buffer, file found
【解决方案2】:

如果要打印打开的文件的内容,只需使用:print filen.read()

【讨论】:

  • 我添加了 "$print filen.read()" 我得到了 IOError: File not open for reading 所以我添加了 "$open(filen,'r') " 但这次我得到了 >> open(filen,'r') TypeError: coercing to Unicode: need string or buffer, file found
  • 为此,您需要先打开文件:filen=open(filename, 'r'),然后才使用:print filen.read()
【解决方案3】:

最简单的:

from sys import argv
script,filename = argv 
with open(filename) as f:
    print f.readlines()

转储文件内容 或:

from sys import argv
script,filename = argv 
with open(filename) as f:
    lines=f.readlines()
for line in lines:
    print line

1×1 打印行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2013-04-06
    • 2011-12-04
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多