2017-04-24 94 views
1

我有一些問題需要在Python中打開並讀取txt文件。 txt文件包含文本(cat text.txt在終端中正常工作)。但在Python中,我只能得到5個空行。讀取txt文件,結果爲空行

print open('text.txt').read() 

你知道爲什麼嗎?

+3

你能告訴我們一個txt文件可能包含什麼的例子嗎? – GiantsLoveDeathMetal

+0

你的程序還有更多嗎?還是隻有一行? – khelwood

+0

你確定讀取方法可以鏈接到打開的方法嗎? 您試過 file = open('text.txt') print file.read() – mnemosdev

回答

1

當你打開文件時,我想你必須指定你想如何打開它。在你的例子中,你應該打開它看起來像這樣:

print open('text.txt',"r").read() 

希望這個伎倆。

+3

「r」是可選的,默認情況下該文件是可以讀取的。 – Shiping

2

如果這會打印文件中的行,那麼您的程序選擇的文件可能是空的?我不知道,但嘗試這個辦法:

import tkinter as tk 
from tkinter import filedialog 
import os 

def fileopen(): 
    GUI=tk.Tk() 
    filepath=filedialog.askopenfilename(parent=GUI,title='Select file to print lines.') 
    (GUI).destroy() 
    return (filepath) 

filepath = fileopen() 
filepath = os.path.normpath(filepath) 

with open (filepath, 'r') as fh: 
    print (fh.read()) 

或替代,使用的印刷線這個方法:

fh = open(filepath, 'r') 
for line in fh: 
    line=line.rstrip('\n') 
    print (line) 
fh.close() 

,或者如果你想加載到一個字符串列表行:

lines = [] 
fh = open(filepath, 'r') 
for line in fh: 
    line=line.rstrip('\n') 
    lines.append(line) 
fh.close() 

for line in lines: 
    print (line) 
4

我解決了它。是一個utf-16文件。

print open('text.txt').read().decode('utf-16-le') 
+0

ahh ...對不起,應該想到編碼._。 – citizen2077