【问题标题】:python TypeError: argument 1 must be string or read-only character buffer, not Nonepython TypeError:参数1必须是字符串或只读字符缓冲区,而不是无
【发布时间】:2015-02-28 21:40:29
【问题描述】:

这是我的代码: def main():

    if len(sys.argv) != 3:

        fname = "OP.tex"
        dot_ind = fname.index(".") + 1
        ofname = fname[:dot_ind] + "1." + fname[dot_ind:]

    else:

        fname = sys.argv[1]
        ofname = sys.argv[2]
    print (fname, "+",ofname)
    writeout(ofname, replacement(readin(fname)))
def replacement(content):
   pattern = re.compile(r'(?<=\\\\\[-16pt]\n)([\s\S]*?)(?=\\\\\n\\thinhline)')
   re.findall(pattern, content)

if __name__ == "__main__":
    main()

我收到以下错误:

File "test.py", line 30, in main
writeout(ofname, replacement(readin(fname)))
File "/home/utilities.py", line 138, in writeout
out.write(content)
TypeError: argument 1 must be string or read-only character buffer, not None

writeout 是另一个文件中的一个函数,它告诉 python 在哪里输出内容:

def writeout(filename, content, append=False):
    """
    Writes content to file filename.
    """

    mode = "w"

    #append to the file instead of overwriting
    if append:
        mode = "a"

    #write content
    with open(filename, mode) as out:
        out.write(content)

fname 和 ofname(输入和输出文件名)是正确的,为什么程序说参数是 None 时是字符串?

非常感谢。

【问题讨论】:

    标签: python regex python-2.7 typeerror


    【解决方案1】:

    您的replacement 函数必须返回一个字符串,目前它返回None。所以,换个说法

    re.findall(pattern, content)
    

    类似

    return ' '.join(re.findall(pattern, content))
    

    请注意,您不能只返回re.findall 的结果,因为这是一个列表,而不是字符串;您必须以一种或另一种方式从该结果中列出一个列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      • 2023-03-03
      相关资源
      最近更新 更多