Collecting every txt file from computer in python and printing it - python

I am trying to collect every txt file from my computer and write it into the terminal when I run the script. I do not know how to do it. Is there a way to read every txt file in the computer then print the contents? (not a certain folder or directory).

In Python, the glob module would give you a list of filenames matching a given string. In your case, glob.glob('dir/*.txt') would give you a list of filenames in directory dir that end in .txt. You can then open each file and print() it to the terminal. Depending on your OS, you might be able to do it in your terminal without writing a separate script.

Related

How to retrieve the unsaved output of a statement in python?

I ran this line to retrieve the paths of all the files in a directory and its subdirectories and forgot to save it in a variable and it takes hours to run it again because of the size of the dataset.
list(glob.glob(str(train_root)+'/**/info.txt',recursive=True))
Is it saved in a variable name reserved by python like temp?
then I can run my_list=temp.
If you already ran the code, python released the memory after the code finished executing. You will likely have to rerun it to get the output.
If you ran this in IDLE, then you can certainly save to a file with something like:
f = open('<output_file_name>','w') and then print(<string_of_data>, file=f) or f.write(<string_of_data>). Finish off with f.close()
Running that will save an output text file containing that variable. You may need to cast the array as a string and specify a path for the output file.

loop in bash/python to call a command including name fixation

I have a line of code that works on a single file:
sextractor ABC347583_ima.fits -CATALOG_NAME ABC347583_ima.cat
this piece of line takes the .fits file and creates a catalog file with the same name but .cat extension
Now, I have over 100+ .fits files(All my files start with the name ABC then numbers and end with _ima) and I would like to make a bash/python script that will read the .fits files 1 by 1 and execute the above code with the corresponding file names as input & output.
Basicly ABC347583_ima.fits , ABC57334_ima.fits etc. will enter and ABC347583_ima.cat , ABC57334_ima.cat etc. will be created.
This is beyond my limited knowlegde and what I only know about this is to use the code with
for i in `cat files`
echo $i
However, this does not exactly match with the command line because of both input & output. Any suggestions about how to pass this will be appreciated.
To iterate in python over all files in a dictonary use os.listdir().
Then you can loop over the filenames.
in the "callthecommandhere" function you can parse the filenames and read the file content and write a new file. I hope I understand you right and that is a help for you.
Like so:
import os
for filename in os.listdir('dirname'):
callthecommandhere(blablahbla, filename, foo)
Br christoph

File names have a `hidden' m character prepended

I have a simple python script which produces some data in a Neutron star mode. I use it to automate file names so I don't later forget the inputs. The script succesfully saves the file as
some_parameters.txt
but when I then list the files in terminal I see
msome_parameters.txt
The file name without the "m" is still valid and trying to call the file with the m returns
$ ls m*
No such file or directory
So I think the "m" has some special meaning of which numerous google searches do not yields answers. While I can carry on without worrying, I would like to know the cause. Here is how I create the file in python
# chi,epsI etc are all floats. Make a string for the file name
file_name = "chi_%s_epsI_%s_epsA_%s_omega0_%s_eta_%s.txt" % (chi,epsI,epsA,omega0,eta)
# a.out is the compiled c file which outputs data
os.system("./a.out > %s" % (file_name) )
Any advise would be much appreciated, usually I can find the answer already posted in the stackoverflow but this time I'm really confused.
You have a file with some special characters in the name which is confusing the terminal output. What happens if you do ls -l or (if possible) use a graphical file manager - basically, find a different way of listing the files so you can see what's going on. Another possibility would be to do ls > some_other_filename and then look at the file with a hex editor.

How to write a whole string to a file in Python and where does the file go?

I am doing an assignment on text formatting and alignment (text wrapping) and I need to write my formatted string to new file. But once I have written to the file (or think I've written) where does that file go? Does it actually create a file on my desktop or am I being stupid?
This is my code:
txtFile = open("Output.txt", "w")
txtFile.write(string)
txtFile.close()
return txtFile
Cheers,
JT
The text is written to a file called "Output.txt" in your working directory (which is usually the directory from which the script has been executed).
To display the working directory, you can use:
>>> import os
>>> os.getcwd()
'/home/adam'
When you open a file without specifying a file path, the file will be created in the python scripts working directory.
Usually that is the location of your script but there are times when it may be a different place.
The os module in python will provide functions for checking and changing the working directory within python itself.
most notably:
os.chdir(path)
os.fchdir(fd)
os.getcwd()
It will create a new file called "Output.txt" in the same directory that you executed your script from. It may mean that the file can't be written to, if you're in a directory that doesn't have the appropriate permissions for your user.

Opening .exe from .txt error

I'm currently creating a script that will simply open a program in the SAME directory as the script. I want to have a text file named "target.txt", and basically the script will read what's in "target.txt" and open a file based on its contents.
For example.. The text file will read "program.exe" inside, and the script will read that and open program.exe. The reason I'm doing this is to easily change the program the script opens without having to actually change whats inside.
The current script Im using for this is:
import subprocess
def openclient():
with open("target.txt", "rb") as f:
subprocess.call(f.read())
print '''Your file is opening'''
Its giving me an error saying it cannot find target.txt, even though I have it in the same directory. I have tried taking away the .txt, still nothing. This code actually worked before, however; it stopped working for some strange reason. I'm using PythonWin compiler instead of IDLE, I don't know if this is the reason.
There are two possible issues:
target.txt probably ends with a newline, which messes up subprocess.call()
If target.txt is not in the current directory, you can access the directory containing the currently executing Python file by parsing the magic variable __file__.
However, __file__ is set at script load time, and if the current directory is changed between loading the script and calling openclient(), the value of __file__ may be relative to the old current directory. So you have to save __file__ as an absolute path when the script is first read in, then use it later to access files in the same directory as the script.
This code works for me, with target.txt containing the string date to run the Unix date command:
#!/usr/bin/env python2.7
import os
import subprocess
def openclient(orig__file__=os.path.abspath(__file__)):
target = os.path.join(os.path.dirname(orig__file__), 'target.txt')
with open(target, "rb") as f:
subprocess.call(f.read().strip())
print '''Your file is opening'''
if __name__ == '__main__':
os.chdir('foo')
openclient()

Categories

Resources