Python Forum
Writing into 2 text files from the same function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writing into 2 text files from the same function
#1
Hi

The following snippet seems to work, but I'm thinking I've been "lucky" and I'm wondering if it's the good way ? indeed neither f1 nor f2 have been passed as argument.

Thanks to hghtlight what's the good pratice

Paul

import os

Path = str(os.getcwd())
n = 10


#####
def MyFunction(n):
    
    f1.write(f"Square value of {n} is {n**2}\n")
    f2.write(f"Cubic value of {n} is {n**3}\n")
    
    

with open(Path + '/file1.txt', 'w') as f1, open(Path + '/file2.txt', 'w') as f2 :
    
    for i in range(1, n):
        MyFunction(i)
Reply
#2
In a certain way the answer may have ever been in the remark; but still wondering if it's thet correct way

import os

Path = str(os.getcwd())
n = 10


#####
def MyFunction(f, g, n):
    
    f.write(f"Square value of {n} is {n**2}\n")
    g.write(f"Cubic value of {n} is {n**3}\n")
    
    

with open(Path + '/file1.txt', 'w') as f1, open(Path + '/file2.txt', 'w') as f2 :
    
    for i in range(1, n):
        print(f"i = {i}")
        MyFunction(f1, f2, i)
Reply
#3
what are you trying to write to?
single letter object names leave no clue, and in general, are poor writing style, exceptions perhaps when writing MCU code with very limited memory.
At any rate, your syntax is fine.
Reply
#4
MyFunction(f, g, n) is a bad function.

1. The name is meaningless.
2. The argument names are meaningless.
3. It makes your code harder to read than not using a function.
4. The function has no purpose that is easily described in a few short sentences.
5. What it does do is silly.

When you write a function it should have a well defined purpose. Let's say the purpose of your function is: Write a function "table" to a file. This would be my first attempt:
def write_function_table(function, values, filename):
    with open(filename, "w") as file:
        for value in values:
            print(value, function(value), file=file)

write_function_table(lambda x: x**2, range(1, 11), "squares.txt")
This produces a file that looks like this:
Output:
1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100
It would be nice if the file "looked pretty", so I add a format string.
def write_function_table(function, values, filename, fmt_str="{inp}, {out}"):
    with open(filename, "w") as file:
        for value in values:
             print(fmt_str.format(inp=value, out=function(value)), file=file)


write_function_table(lambda x: x**2, range(1, 11), "squares.txt", "square {inp} = {out}")
This produces:
Output:
square 1 = 1 square 2 = 4 square 3 = 9 square 4 = 16 square 5 = 25 square 6 = 36 square 7 = 49 square 8 = 64 square 9 = 81 square 10 = 100
It would be nice if I could use this function and have it write to stdout instead of a file, or maybe write multiple tables to one file.
def write_function_table(function, values, fmt_str="{inp}, {out}", file=None):
    for value in values:
        print(fmt_str.format(inp=value, out=function(value)), file=file)


values = range(1, 11)
with open("function tables.txt", "w") as file:
    print("Squares", file=file)
    write_function_table(lambda x: x**2, values, "{inp} = {out}", file)
    print("\nSquare roots", file=file)
    write_function_table(lambda x: x**0.5, values, "{inp} = {out}", file)
write_function_table(lambda x: x**3, values, "{inp}**3 = {out}")
This creates a function tables.txt file that looks like this:
Output:
Squares 1 = 1 2 = 4 3 = 9 4 = 16 5 = 25 6 = 36 7 = 49 8 = 64 9 = 81 10 = 100 Square roots 1 = 1.0 2 = 1.4142135623730951 3 = 1.7320508075688772 4 = 2.0 5 = 2.23606797749979 6 = 2.449489742783178 7 = 2.6457513110645907 8 = 2.8284271247461903 9 = 3.0 10 = 3.1622776601683795
And also writes this to stdout.
Output:
1**3 = 1 2**3 = 8 3**3 = 27 4**3 = 64 5**3 = 125 6**3 = 216 7**3 = 343 8**3 = 512 9**3 = 729 10**3 = 1000
And to make it easier for others to use my function I would provide documentation.
def write_function_table(function, values, fmt_str="{x}, {fx}", file=None):
    """Write a "function table" to the file.
    function : The function to evaluate for x
    values : Iterable of x values
    fmt_str : String compatible with format() command.  Use "x" for x and "fx" for function(x)
    file : File to write results.  If None, writes to stdout
    """
    for x in values:
        print(fmt_str.format(x=x, fx=function(x)), file=file)


values = range(1, 11)
with open("squares.txt", "w") as file:
    write_function_table(lambda x: x**2, values, "square {x} = {fx}", file)
write_function_table(lambda x: x**3, values, "{x}**3 = {fx}")
Now not only can I use it, but others can use it too. And when my users ask me to add generating square root tables or combining multiple tables in one file it will be easy for me to quickly modify my program to add those capabilities.
rob101 likes this post
Reply
#5
Naming is key, because functions are a tool for abstraction, as well as reuse.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Function parameter not writing to variable Karp 5 921 Aug-07-2023, 05:58 PM
Last Post: Karp
  azure TTS from text files to mp3s mutantGOD 2 1,695 Jan-17-2023, 03:20 AM
Last Post: mutantGOD
  Create a function for writing to SQL data to csv mg24 4 1,149 Oct-01-2022, 04:30 AM
Last Post: mg24
  Delete empty text files [SOLVED] AlphaInc 5 1,546 Jul-09-2022, 02:15 PM
Last Post: DeaD_EyE
  select files such as text file RolanRoll 2 1,156 Jun-25-2022, 08:07 PM
Last Post: RolanRoll
  Two text files, want to add a column value zxcv101 8 1,899 Jun-20-2022, 03:06 PM
Last Post: deanhystad
  select Eof extension files based on text list of filenames with if condition RolanRoll 1 1,507 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  Separate text files and convert into csv marfer 6 2,859 Dec-10-2021, 12:09 PM
Last Post: marfer
  Using .hdf5 files only once they are finished writing pyhill00 7 2,785 Nov-25-2021, 06:01 PM
Last Post: pyhill00
  Sorting and Merging text-files [SOLVED] AlphaInc 10 4,872 Aug-20-2021, 05:42 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020