2015-11-07 30 views
0

我試圖插入一個文件,我不斷上線line = infile.redline()這段代碼有什麼問題?我想插入這個文件

def main(): 
    # Declare variables 
    line = '' 
    counter = 0 

    # Prompt for file name 
    fileName = input('Enter the name of the file: ') 

    # Open the specified file for reading 
    infile = open('test.txt', 'r') 

    # Priming read 
    line = infile.redline() 
    counter = 1 

    # Read in and display first five lines 
    while line != '' and counter <= 5: 
    # Strip '\n' 
    line = line.rtrip('\n') 
    print(line) 
    1ine = infile.readline() 
    # Update counter when line is read 
    counter +=1 

# Close file 
infile.close() 

# Call the main function. 
    main() 

回答

1

rtrip得到一個語法錯誤,應該是rstripredline應該是readlineinfile.close()應該縮進,並且main()不應該是。

然而,最嚴重的問題是在這裏:

1ine = infile.readline() 

即第一個字符是一個,而不是L.

0

這不是redlinereadline

line = infile.redline() 
+0

感謝您的幫助,工作:) –

1

知標準庫可以讓你的生活更簡單!

from itertools import islice 

def main(): 
    fname = input('Enter the name of the file: ') 

    with open(fname) as inf: 
     for line in islice(inf, 5): # get the first 5 lines 
      print(line.rstrip()) 

if __name__=="__main__": 
    main()