读取文件和分隔符(python)

2024-04-25 01:33:15 发布

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

我当前的项目应该获取输入的数据并将其发送到一个文件中,该文件稍后将被读取以创建直方图。我可以很好地将数据发送到文件中,但是要将其返回并组织起来是很困难的。下面是我试过的:

substringInt = 0
f = open("storedInfo", "r")
for i in f:  # searches line by line
    while i in f.read != ",":  # appends weights to list
        substringInt += 1
array.append(f.read(substringInt))

当我运行它时,我收到以下信息: TypeError: argument of type 'builtin_function_or_method' is not iterable

我是一名编程新手,所以如果你能为我把你的答案简化,那就太棒了。如果我的问题没有道理,请随时问我。


1条回答
网友
1楼 · 发布于 2024-04-25 01:33:15

Python读取文件不是以这种方式使用的。你应该这样写:

with open('file.txt') as f:
  content = f.read()  # Read all the content in the file as a long string
arrays = content.split(',')  # Split the long string in to an array of strings with comma ','

相关问题 更多 >