简体   繁体   中英

Saving data in TXT file using python to the local driver

i make a simple code in python to output data in txt format file in my local driver pc using windows OS but nothing happened . i want to know the problem

here is the code :

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

def a():

    return (2+3)

def x():

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

f.write(x())
f.close()

please try this

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()

since function x does not return anything you cant print it to file

Writing into files both strings and variables. Please Note: There are many ways to get it done. This is just one.

#!/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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM