我在Python中打开和读取txt文件时遇到了一些问题。txt文件包含文本(cat text.txt在终端中工作正常)。但在Python中,我只得到5行空行。
print open('text.txt').read()你知道为什么吗?
发布于 2017-04-24 18:48:22
我解决了。是一个utf-16格式的文件。
print open('text.txt').read().decode('utf-16-le')发布于 2017-04-24 18:19:41
如果这会打印文件中的行,那么您的程序选择的文件可能是空的?我不知道,但试试这个:
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)发布于 2017-04-24 18:06:21
当你打开文件时,我想你必须指定你想要如何打开它。在您的示例中,您应该打开它进行阅读,如下所示:
print open('text.txt',"r").read()希望这能奏效。
https://stackoverflow.com/questions/43585023
复制相似问题