2016-08-23 61 views
-3

我從過去幾周學習Python的艱辛的道路的argv和文件

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

+1

與美元符號有什麼出1行? –

回答

0

則可以使用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)的ReadLine

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)readlines方法。

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

+1

鏈接只有答案應該避免... – Julien

+1

如果你先寫你要['.seek(0)'(https://docs.python.org/2/tutorial/inputoutput.html#方法-的文件對象)讀 – GP89

+0

之前我加「$打印filen.read()」我得到IO錯誤:文件無法打開閱讀,所以我已經添加「$打開(filen,‘R’)」,但這次我拿到>>開放(filen,「R」) 類型錯誤:強迫爲Unicode:需要字符串或緩衝區,文件中發現 – root

0

如果要打印您打開的文件的內容,請使用:print filen.read()

+0

我添加「$打印filen.read()」我得到IO錯誤:文件無法打開閱讀,所以我已經添加「$打開(filen,‘R’)」,但這次我得到>>開放(filen,「R」) 類型錯誤:強迫爲Unicode:需要字符串或緩衝區,文件發現 – root

+0

對於您需要首先打開文件: 'filen =開放(文件名, 'R')'和僅然後使用: '打印filen.read()' –

0

在最簡單的:

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