Python 在阅读 .txt 文档时添加额外的 \n 字符和空格

Python puts additional \n characters and spaces when reading .txt documents

我正在为 Python 中的顶点列表编写深度和广度优先搜索。我正在尝试读取如下所示的 .txt 文件:

    50
    60
    45
    12
    68
    21
    13
    24

我的代码如下:

def readFile(x):
    fin = open(x, 'r')
    readline = fin.read()
    x,y = [], []

    for line in readline:
        row = line.split()
        x.append(row[0])
        print(x)
        y.append(row[1])

不幸的是,当代码将 txt 文件读入 Python 时,这只会将 6 读入程序并终止说索引超出 y 的范围。在我的 .txt 文件中,除了每组点的末尾之外,没有 spaces 或 \n 字符。

关于为什么要添加所有这些额外的白色 space 和 \n 字符有什么想法吗?

旁注:当我使用 sys.stdout.write(line) 时,输出正是我要查找的内容,但我无法为其编制索引。

with open(x) as fin:
        for line in fin:
            sys.stdout.write(line)

如有任何帮助,我们将不胜感激!

def readFile(x):
    fin = open(x, 'r')
    readline = fin.readlines()
    x,y = [], []
    for line in readline[::2]: #to skip the extra line [before editing question]
        x.append(line[0])
        y.append(line[1])

已编辑: 您必须使用 readlines() 或 read().split()[两者都会将内容读入内存],或者您可以只迭代对象[这将一次只保留一行]

你必须使用 strip 来删除多余的白色字符而不是拆分

def readFile(x):
    with open(x, 'r') as fin:
        x, y = [], []
        for line in fin:
            row = line.strip()
            x.append(row[0])
            y.append(row[1])
        print(x,y)

readFile('a.txt')        

输出: ['5', '6', '4', '1', '6', '2', '1', '2'] ['0', '0', '5', '2', '8', '1', '3', '4']

你很亲密,移除readline = fin.read();这是在读第一个“6”。

然后,将for line in readline:改成for line in fin:

最后,你的文件好像有空行,只好跳过:

line = line.strip()
if line != '': 
    row = line
    x.append(row[0])
    print(x)
    y.append(row[1])

因为您没有足够的答案,这里有另一个!

def readFile(x):
    with open(x, 'r') as fin:
        x, y = [], []
        for line in fin:
            row = line.rstrip()
            x.append(row[0])
            print(x)
            y.append(row[1])