我正在尝试使用一个非常基本的文本文件作为设置文件。三行按此顺序/格式重复,用于管理我的程序的一些设置/输入。文本文件如下:
Facebook
1#3#5#2
Header1#Header2#Header3#Header4
...
这是使用以下Python代码读取的:
f = open('settings.txt', 'r')
for row in f:
platform = f.readline()
rows_to_keep = int(f.readline().split('#'))
row_headers = f.readline().split('#')
clean_output(rows_to_keep, row_headers, platform)
我希望在平台中读取单个字符串,在第二个中读取int数组,在第三个中读取字符串数组。然后将这些信息传递给函数,并重复多次。
然而,以下三件事正在发生:
- Int不转换,我得到一个
TypeError
- 文本文件中的第一行被忽略,我得到了要保留在平台中的行
- 每条线末端的
n
我怀疑这些是相关的,所以我只发布了一个问题。
-
你不能在列表上调用int,你需要做一些列表理解,比如
rows_to_keep=[int(a)for a in f.readline().split('#')]
-
您正在读取文件中的一行,然后再读取另一行。您应该进行某种切片(请参阅Python如何一次读取N行),或者在每三次迭代后用三行调用一个函数。
-
使用
.strip()
删除行尾和其他空白。
试试这个:
with open('settings.txt', 'r') as f:
platform, rows_to_keep, row_headers = f.read().splitlines()
rows_to_keep = [int(x) for x in rows_to_keep.split('#')]
row_headers = row_headers.split('#')
clean_output(rows_to_keep, row_headers, platform)
这里发生了一些事情。首先,当您在第二行执行拆分时,您正试图将list
强制转换为类型int
。那行不通。相反,您可以使用map
。
rows_to_keep = map(int,f.readline().strip().split("#"))
此外,您可以看到上面的strip()
方法。这将从您的行中删除尾随的空白字符,即:n
。
尝试该更改,并在每次readline()
调用中使用strip()
。
通过尽可能少的更改,我试图解决您的问题,并向您展示哪里出了问题@丹尼尔的答案是我将如何亲自解决这些问题。
f = open('settings.txt', 'r')
#See 1. We remove the unnecessary for loop
platform = f.readline()
#See 4. We make sure there are no unwanted leading or trailing characters by stripping them out
rows_to_keep = f.readline().strip().split('#')
#See 3. The enumerate function creates a list of pairs [index, value]
for row in enumerate(rows_to_keep):
rows_to_keep[row[0]] = int(row[1])
row_headers = f.readline().strip().split('#')
#See 2. We close the file when we're done reading
f.close()
clean_output(rows_to_keep, row_headers, platform)
- 您不需要(也不希望)
f
上的for循环,以及对readline的调用。你应该选择其中一个 - 您需要使用
f.close()
关闭f
- 无法将
list
转换为int
,您希望将list
中的元素转换为int
。这可以通过for
循环来实现 - 您可能想要调用
.strip
来消除尾随的换行符