语法错误def数据(路径)的语法无效

时间:2019-08-24 23:22:24

标签: python function

这是我遇到错误的代码行

def Data('C:/Users/username/Desktop/d.txt'):
    fp = open('C:/Users/username/Desktop/d.txt')

我收到以下错误:

File "read.py", line 17
    def DataExtract('C:/Users/username/Desktop/d.txt'):
                                                    ^
SyntaxError: invalid syntax

不确定是什么问题以及导致无效语法的原因

谢谢!

这是我正在处理的代码:

def DataExtract('C:/Users/username/Desktop/d.txt'):
fp = open('C:/Users/username/Desktop/d.txt')
data = {}
line = fp.read().split("\n")[2:7:5]:
while line:
    name, _, cont = line.partition(":")
    keys, _, values = cont.partition("=")
    keys = keys.split(",")
    values = values.split(",")
    temp_d = {}
    for i in range(len(keys)):
        key = key[i].strip()
        val = values[i].strip()
        temp_d[key] = float(val)
    data[name] = temp_d
    line = fp.readline()
fp.close()

返回数据

x = DataExtract('C:/Users/username/Desktop/d.txt')
mul_p = x['d1']['p'] * x['d2']['p']
print(mul_p)

1 个答案:

答案 0 :(得分:1)

如之前@LhasaDad的评论中所述。

我在您所附的代码中发现了两个错误。

第一个错误:

首先是“ def”语句。该函数需要一个变量占位符,而不是变量的值。例如:

>>> def fun('hello'):
  File "<stdin>", line 1
    def fun('hello'):
                  ^
SyntaxError: invalid syntax
>>> def fun(5):
  File "<stdin>", line 1
    def fun(5):
            ^
SyntaxError: invalid syntax

正确的方法是


>>> def fun(var):
...     print(var)
...
>>> #Then call the function using below method
...
>>> fun('hello')
hello
>>> fun(5)
5

第二个错误:

应始终存在和缩进(def语句后的制表符或4个空格)

因此,希望您能解决此问题

def DataExtract(file_path):
    fp = open(file_path)
    data = {}
    line = fp.read().split("\n")[2:7:5]
    while line:
        name, _, cont = line.partition(":")
        keys, _, values = cont.partition("=")
        keys = keys.split(",")
        values = values.split(",")
        temp_d = {}
        for i in range(len(keys)):
            key = keys[i].strip()
            val = values[i].strip()
            temp_d[key] = float(val)
        data[name] = temp_d
        line = fp.readline()
    fp.close()


# Now call the function as
DataExtract('C:/Users/username/Desktop/d.txt')

您还可以从def阅读如何使用python函数 https://www.w3schools.com/python/python_functions.asp