Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将数字从一个文本文件减到另一个文本文件?_Python - Fatal编程技术网

Python 如何将数字从一个文本文件减到另一个文本文件?

Python 如何将数字从一个文本文件减到另一个文本文件?,python,Python,因此,我必须从包含以下行的文本文件中读取: 4-1 12-3 在我读了那个文件之后,我必须在另一个文件中写入行的结果。e、 g.-> 4-1=3 12-3=9 到目前为止,我已经编写了此代码,但我收到了某种错误: with open('C:\users\bacut\Desktop\expresii.txt\', 'r'') as fp: for line in enumerate(fp): nr1 = 0 nr2 = 0

因此,我必须从包含以下行的文本文件中读取:

4-1
12-3
在我读了那个文件之后,我必须在另一个文件中写入行的结果。e、 g.->

4-1=3
12-3=9
到目前为止,我已经编写了此代码,但我收到了某种错误:

with open('C:\users\bacut\Desktop\expresii.txt\', 'r'') as fp:
        for line in enumerate(fp):
            nr1 = 0
            nr2 = 0
            ok = 0
            for c in line:
                if c != '-' and ok == 0:
                    nr1 = nr1 * 10 + int(c)
                if c == '-':
                    ok = 1
                if c  != '-' and ok == 1:
                    nr2 = nr2 * 10 + int(c)
            total = nr1 - nr2
            print("{line}={total}".format(line=line, total=total))
这就是错误:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 
2-3: truncated \uXXXX escape
我该怎么做?我不知道如何在另一个文件中写入结果,但在我的逻辑中,这段代码必须至少生成12-3=9。 谢谢,我非常感谢您的帮助。

您可以尝试以下代码:

with open(r'C:\users\bacut\Desktop\expresii.txt', 'r') as fp:
        for line in fp:
            stripline = line.strip()
            linelist = stripline.split("-") # first line: list ["4", "1"]
            result = int(linelist[0]) - int(linelist[1])
            stripline+=("=" + str(result)+"\n")
            with open(r'C:\users\bacut\Desktop\result.txt', 'a') as fr:
                fr.write(stripline)

把你需要的代码放在远处,突出你正在挣扎的部分。你认为什么是“数学表达式”?只有像
4-1
中那样的整数运算,还是包括变量或积分在内的更复杂的运算?操作符是否与Python中的相同,例如
**
是power操作符吗?请使用
r'C:\users\bacut\Desktop\expresii.txt'
。注意
r
前缀和删除的尾随反斜杠。哦,你在
'r'
中还有一个额外的单引号。完成了。现在我得到了这个错误:
发生了异常:ValueError无效literal for int(),基数为10:'4-1\n'文件“C:\Users\bacut\Desktop\exercitii programare.py”,第9行,在nr1=nr1*10+int(C)
感谢您的回答!我试图运行它,但得到了以下结果:
出现异常:AttributeError'tuple'对象没有属性'strip'文件“C:\Users\bacut\Desktop\lista.py”,第3行,stripline=line.strip()
这是由enumerate引起的,现在应该更正了。再次感谢。很抱歉打扰你,我真的很感激你为我所做的工作。我再试了一次,现在它显示了另一个错误:
发生了异常:AttributeError'str'对象没有属性'append'文件“C:\Users\bacut\Desktop\lista.py”,第6行,在第行。append(“=”+str(result))
我编辑了答案,现在试试看,它在本地对我很有用!!!!你是最棒的。