I need to output the values that I calculate from my code to a text file in a certain format. First I will explain how my output from the python code look like and then explain how I want the text file to be.
Column A
1
2
3
4
Column B
3
4
1
9
Column C
20
56
89
54
How I want the text file is as below
Number Column A Column B Column C
0 1 3 20
1 2 4 56
2 3 1 89
3 4 9 54
all the output on the screen are due to print statement of variable value that I am calculating using the code. Can you help me on how I can do this?
If the items come in that order you will have to save it to a list, dictionary or something and then print. Look at this example:
output = [[] for i in range(5)] # [[],[],[],[],[]]
for ind, item in enumerate(["Column A","1","2","3","4"]):
print(item)
output[ind].append(item)
for ind, item in enumerate(["Column B","3","4","1","9"]):
print(item)
output[ind].append(item)
with open("output.txt", "w") as f:
for row in output:
f.write('\t'.join(row))
f.write('\n')
prints:
Column A
1
2
3
4
Column B
3
4
1
9
Output:
[['Column A', 'Column B'], ['1', '3'], ['2', '4'], ['3', '1'], ['4', '9']]
"output.txt":
Column A Column B
1 3
2 4
3 1
4 9
If you have a print()
statement that already does exactly what you want then you only have to redirect the output to a textfile.
with open(r'path_to\my_file.txt','w') as textfile:
... your existing code goes here ...
...
print ( ... whatever your print statement does ..., file=textfile)
If your print
statement is creating that output exactly the way you want, I strongly suggest using the new-ish pathlib
module (available in Python >= 3.4) to create your file. It is great for working with path-like objects (both Windows and for other OSes).
If your file content is stored as a string in data
, you can just do this:
from pathlib import Path
file_path = Path('some_file.txt') # a relative file path - points within current directory
file_path.write_text(data) # overwrites existing file of same name
file_path.write_text(data, mode='a') # appends to an existing file of same name
Here's a little Path
tutorial.
It's Paths - Paths all the way down
To simplify: you can build up any path (directory and file path objects are treated exactly the same) as an object, which can be an absolute path object or a relative path object.
Simple displaying of some useful paths- such as the current working directory and the user home- works like this:
from pathlib import Path
# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)
# Current directory (absolute):
cwd = Path.cwd()
print(cwd)
# User home directory:
home = Path.home()
print(home)
# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)
To navigate down the file tree, you can do things like this. Note that the first object, home
, is a Path
and the rest are just strings:
file_path = home/'Documents'/'project'/'data.txt' # or
file_path = home.join('Documents', 'project', 'data.txt')
To read a file located at a path, you can use its open
method rather than the open
function:
with file_path.open() as f:
dostuff(f)
But you can also just grab the text directly!
contents = file_path.read_text()
content_lines = contents.split('\n')
...and WRITE text directly!
data = '\n'.join(content_lines)
file_path.write_text(data) # overwrites existing file
Check to see if it is a file or a directory (and exists) this way:
file_path.is_dir() # False
file_path.is_file() # True
Make a new, empty file without opening it like this (silently replaces any existing file):
file_path.touch()
To make the file only if it doesn't exist, use exist_ok=False
:
try:
file_path.touch(exist_ok=False)
except FileExistsError:
# file exists
Make a new directory (under the current directory, Path()
) like this:
Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists
Get the file extension or filename of a path this way:
file_path.suffix # empty string if no extension
file_path.stem # note: works on directories too
Use name
for the entire last part of the path (stem and extension if they are there):
file_path.name # note: works on directories too
Rename a file using the with_name
method (which returns the same path object but with a new filename):
new_path = file_path.with_name('data.txt')
You can iterate through all the "stuff' in a directory like so using iterdir
:
all_the_things = list(Path().iterdir()) # returns a list of Path objects
I searched and found that it was better for me to print the values in the terminal exactly like how I want in the text file. So I rewrote my code to display the values as one complete tab limited row and it worked. I appreciate all your help.
I am not sure if this can be marked as an answer. If not let me know, I will add as a comment.
You can use numpy.savetxt
and use the header-keyword
https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html