【问题标题】:File handling in Python for beginners面向初学者的 Python 文件处理
【发布时间】:2016-09-29 13:41:05
【问题描述】:

您好,我是 python 新手,我遇到了这个错误:

C:\Users\Dylan Galea\Desktop\Modelling and CS>python file_handling.py

文件“file_handling.py”,第 4 行

np.savetxt(\Users\Dylan Galea\Desktop\Modelling and

CS\test.txt,twoDarray,delimeter='\t') ^ SyntaxError:行继续字符后出现意外字符

我的代码是这样的:

import numpy as np

twoDarray =np.array([[1,2,3],[4,5,6]])
np.savetxt(\Users\Dylan Galea\Desktop\Modelling and CS\test.txt,twoDarray,delimeter='\t')

有人可以帮忙吗?

【问题讨论】:

  • 您需要使用引号将路径指定为字符串,即"Users/Dylan Galea/Desktop/Modelling and CS/test.txt"。请注意,\ 需要像 \\ 一样转义,如果您的路径以 \ / 开头,则它应该是绝对的。

标签: python file numpy


【解决方案1】:

请使用 stackoverflow 的代码语法,以便我们更轻松地阅读您的代码。

您似乎拼错了delimiter

【讨论】:

    【解决方案2】:

    您好,欢迎来到 StackOverflow。请使用 StackOverflow 提供的工具来正确构建您的帖子(例如标记代码等),并确保 Python 代码的缩进和换行符是正确的,因为它是语法的一部分。

    关于这个问题,您的路径可能存在问题,该路径未标记为字符串(必须用引号括起来)并且包含反斜杠,这是 Python 中的特殊转义字符。根据您的操作系统(Mac OS、Windows、Linux 等),您可能需要使用正斜杠或双(!)反斜杠。

    试试这个:

    twoDarray = np.array([[1,2,3],[4,5,6]])
    np.savetxt("/Users/Dylan Galea/Desktop/Modelling and CS/test.txt", twoDarray,delimeter='\t')
    

    【讨论】:

      【解决方案3】:

      你的文件名应该是一个字符串。

      np.savetxt(r'\Users\Dylan Galea\Desktop\Modelling and CS\test.txt',twoDarray,delimeter='\t')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-19
        • 1970-01-01
        • 2015-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多