【问题标题】:'NoneType' object is not iterable python3'NoneType' 对象不可迭代 python3
【发布时间】:2019-03-04 18:57:29
【问题描述】:

您好,我一直在编写一些 python 脚本,我的问题是当我在服务器上启动该脚本时。事情是我制作了名为 CSVmanipulation 的模块,其中我有两个函数,一个用于从 .csv 读取,另一个用于写入 .csv 文件。我的主脚本是这样的

import time
import scrape
import re
from urlload import load_urls
from setmanipulation import addToSet
from CSVmanipulation import Reader, Writer

USERSURLS = Reader("users.csv")

for newurl in USERSURLS:
    "do something"

我的 CSV 操作脚本是:

import csv

def Reader(nameOfAFile):
        list = []
        if(os.path.isfile(nameOfAFile) == True):
                with open(nameOfAFile) as fajl:
                        reader = csv.reader(fajl)
                        list = [r for r in reader]
                        fajl.close()
                return list
        else:
                print("file doesnt exist")

在我的机器上本地运行它完全正常,它从 .csv 文件读取,读取的所有内容都存储在我的列表中,但是当我在服务器上尝试这个时,我得到这个输出:

file doesnt exist
'NoneType' object is not iterable

文件存在于本地和服务器上,其中包含内容。 我已经像百万次一样挠头并访问了每个站点,但我不知道到底出了什么问题。我将不胜感激。

【问题讨论】:

    标签: ubuntu python-3.7 import-from-csv


    【解决方案1】:

    所以基本上你的 Reader 方法找不到文件并且返回 NONE。由于 USERURLS 现在为 NONE,因此您不能在其上使用 for 循环。

    USERURLS = Reader("users.csv")之前

    试试print(os.getcwd())

    这将打印程序当前的工作目录,并查看您的“users.csv”文件是否位于该目录。

    【讨论】:

    • 它给了我与“users.csv”相同的路径,但是当我重新上传所有内容时它开始工作,除了“文件不存在”的一件事仍然弹出。我认为每次我使用我的 var USERSURLS 它启动我的 Reader 方法。我希望我的行 USERURLS = Reader("users.csv") 只运行一次,然后将它返回的任何内容存储到这个 var
    • 我已经重读了几次,但我不明白。如果它说“文件不存在”,则意味着 os.path.isfile(nameOfAFile) 返回 false,从而使函数返回 None。这是你想要的吗?
    【解决方案2】:

    对我的代码进行了一点修改: main.py:

    import time
    import scrape
    import re
    from urlload import load_urls, display
    from setmanipulation import addToSet
    from CSVmanipulation import Reader, Writer
    
    USERSURLS = []
    Reader("users.csv", USERSURLS)
    
    for newurl in USERSURLS:
       "do something"
    

    我的 CSV 操作如下所示:

    import os
    import csv
    
    def Reader(nameOfAFile, list):
            statment = os.path.exists(nameOfAFile)
            print(os.getcwd())
            if(statment == True):
                    with open(nameOfAFile) as fajl:
                            reader = csv.reader(fajl)
                            list.extend(r for r in reader)
                            fajl.close()
            else:
                    print("file doesnt exist")
    
            return
    

    我只是在请求为空列表USERSURL = [] 时创建了USERSURL,并且由于列表是一个可变对象,我只是将其发送到方法中,因此每次更改都会生效。

    谢谢你的帮助

    【讨论】:

      猜你喜欢
      • 2016-02-08
      • 2020-05-06
      • 1970-01-01
      • 2021-08-20
      • 2013-12-01
      • 2012-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多