Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.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将TXT文件中的数据保存到本地驱动程序_Python - Fatal编程技术网

使用python将TXT文件中的数据保存到本地驱动程序

使用python将TXT文件中的数据保存到本地驱动程序,python,Python,我用python编写了一个简单的代码,用windows操作系统在本地驱动程序pc中以txt格式文件输出数据,但什么也没发生。我想知道这个问题 代码如下: f = open("my.txt" , "w") def a(): return (2+3) def x(): b = a() print("\n" ,b) f.write(x()) f.close() 请试试这个 f = open("my.txt" , "w") def a(): return (2

我用python编写了一个简单的代码,用windows操作系统在本地驱动程序pc中以txt格式文件输出数据,但什么也没发生。我想知道这个问题

代码如下:

f = open("my.txt" , "w")

def a():

    return (2+3)

def x():

    b = a()
    print("\n" ,b)

f.write(x())
f.close()
请试试这个

f = open("my.txt" , "w")
def a():
    return (2+3)
def x():
    b = a()
    print("\n" ,b)
    return str(b)
f.write(x())
f.close()

由于函数x不返回任何内容,因此无法将其打印到文件中,也无法将字符串和变量写入文件中。 请注意:有很多方法可以做到这一点。这只是其中之一

#!/usr/bin/env python

import sys

# function returning compute results
def fun_compute(num):
    return num * num

# For writing in a file.
# Opened the file in w+ mode
with open("./files/sample.txt", "w+") as sys.stdout:
    print("I am printing fun stuff!")  # writing standard string
    num = 5
    for n in range(num):
        print("fun_compute for - %s" % fun_compute(n))

Mohamed,您可以将字符串写入文件,您的函数x()不返回字符串。只需返回
“{}\n”。format(a())
“\n{}”。format(a())
函数x中没有返回任何内容。将
打印(“\n”,b)
更改为
返回“\n”+str(b)
使用而不是
作为sys.stdout