读取txt文件,结果是空行

2024-04-26 06:33:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中打开和读取txt文件时遇到一些问题。txt文件包含文本(cat文本.txt在航站楼工作正常)。但在Python中我只得到5行空行。在

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

你知道为什么吗?在


Tags: 文件text文本txtreadopencatprint
3条回答

如果这会打印文件中的行,那么程序选择的文件可能是空的?我不知道,但试试这个:

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())

或者,使用这种打印线条的方法:

^{pr2}$

或者,如果要将行加载到字符串列表中:

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

for line in lines:
    print (line)

当你打开文件时,我想你必须指定你想如何打开它。在您的示例中,您应该打开它进行阅读,例如:

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

希望这能起作用。在

我解决了。是一个utf-16文件。在

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

相关问题 更多 >