Creating files in specific path with python - python

is it possible to create a file with a specific extension, name and python with the sys module or any other module?
Thanks!

Using
f = open('myfile.myextension', 'w')
f.write('hello')
f.close()
You can create file with any extension you would like. If you want another software to read it, for example, if you want to create an excel file (xlsx) or pdf you might need additional packages.

This should work with the path and the file name:
import os
PATH = '/home/user/somepath'
FILE = 'somefile.someext'
os.makedirs( PATH, exist_ok=True) # create the PATH if not exists
full_name = os.path.join( PATH, FILE )
with open( full_name ) as fout :
print >>fout, 'some message'

Related

Opening a file with python in the same directory from different locations

I am currently accessing a script that opens a file in the directory it's located in. I am accessing this file from both the main.py file located in the same directory, as well as a testfile which is located in a "Test" subdirectory. Trying to use a file from the Test subdirectory to call the function that opens the file causes the script to try and open it from the Test directory instead of the super directory, since I am opening the file simply by calling it as following:
with open(filename,"w") as f:
Is there a way to define the location of the file in a way that makes it possible for the script opening it to be called from anywhere?
Use __file__ to get the path to the current script file, then find the file relative to that:
# In main.py: find the file in the same directory as this script
import os.path
open(os.path.join(os.path.dirname(__file__), 'file.txt'))
# In Test/test.py: find the file one directory up from this script
import os.path
open(os.path.join(os.path.dirname(__file__), '..', 'file.txt'))
just give the absolute file path instead of giving a relative one
for eg
abs_path = '/home/user/project/file'
with open(abs_path, 'r') as f:
f.write(data)
Try specifying the path:
import os
path = 'Your path'
path = os.path.abspath(path)
with open(path, 'w') as f:
f.write(data)
From what I understood your file is in a directory parent_directory/file_name.txt
and in another folder parent_directory/sub_directory/file_name.txt. All you have to do is paste the below code in both parent and sub directories.
import os
file_name = 'your_file_name'
# if the file is in current directory set the path to file_name
if file_name in os.listdir(os.getcwd()):
path = file_name
# if the path is not in current directory go back to parent directory set the path to parent directory
else:
path = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
print('from',os.getcwd())
with open(path, 'r') as filename:
print(filename.read())

How do I save a csv file to an absolute path using the csv module in Python?

I currently have a program that collects data from .txt files in a folder and then saves that data to a csv file. Due to how I am planning on distributing this program, I need the Python file to live in the folder where these .txt files are located. However, I need the .csv files to be thrown to an absolute file path rather than being created in the same folder as the Python script and .txt documents. Here is what I have currently coded,
def write_to_csv(journal_list):
#writes a list of journal dictionaries to a csv file.
import csv
username = "Christian"
csv_name = username + ".csv"
myFile = open(csv_name, 'w')
with myFile:
myFields = ["filename", "username", "project_name", "file_path",
"date", "start_time", "end_time", "length_of_revit_session",
"os_version", "os_build", "revit_build", "revit_branch",
"cpu_name", "cpu_clockspeed", "gpu_name", "ram_max", "ram_avg", "ram_peak",
"sync_count", "sync_time_total", "sync_time_peak", "sync_time_avg",
"commands_total", "commands_hotkey_percentage", "commands_unique",
"commands_dynamo", "commands_escape_key", "commands_most_used"]
writer = csv.DictWriter(myFile, fieldnames=myFields)
writer.writeheader()
for item in journal_list:
try:
writer.writerow(item)
except:
print("error writing data to:", item)
I appreciate the help.
USing os.path.join() you can select your desire path for your file to be written. Here is an example:
import os
desier_path = '/home/foo/'
file_path = os.path.join(dest_dir, csv_name)
with open(file_path, 'w'):
...
Consider asking for the path from the script, and setting a default if not passed in. This would make your script a lot more flexible than having the path coded in it.
You can use the click package which simplifies this a bit.
import os
import click
def write_to_csv(path, journal_list):
# .. your normal code
file_path = os.path.join(path, '{}.csv'.format(username))
# .. rest of your code here
#click.command()
#click.option('--output_dir', default='/home/foo/bar/', help='Default path to save files')
def main(output_dir):
write_to_csv(output_dir)
if __name__ == '__main__':
main()

Cannot find a file in my tempfile.TemporaryDirectory() for Python3

I'm having trouble working with Python3's tempfile library in general.
I need to write a file in a temporary directory, and make sure it's there. The third party software tool I use sometimes fails so I can't just open the file, I need to verify it's there first using a 'while loop' or other method before just opening it. So I need to search the tmp_dir (using os.listdir() or equivalent).
Specific help/solution and general help would be appreciated in comments.
Thank you.
Small sample code:
import os
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
print('tmp dir name', tmp_dir)
# write file to tmp dir
fout = open(tmp_dir + 'file.txt', 'w')
fout.write('test write')
fout.close()
print('file.txt location', tmp_dir + 'lala.fasta')
# working with the file is fine
fin = open(tmp_dir + 'file.txt', 'U')
for line in fin:
print(line)
# but I cannot find the file in the tmp dir like I normally use os.listdir()
for file in os.listdir(tmp_dir):
print('searching in directory')
print(file)
That's expected because the temporary directory name doesn't end with path separator (os.sep, slash or backslash on many systems). So the file is created at the wrong level.
tmp_dir = D:\Users\foo\AppData\Local\Temp\tmpm_x5z4tx
tmp_dir + "file.txt"
=> D:\Users\foo\AppData\Local\Temp\tmpm_x5z4txfile.txt
Instead, join both paths to get a file inside your temporary dir:
fout = open(os.path.join(tmp_dir,'file.txt'), 'w')
note that fin = open(tmp_dir + 'file.txt', 'U') finds the file, that's expected, but it finds it in the same directory where tmp_dir was created.

Open existing file of unknown extension

I need to open a file for reading, I know the folder it is in, I know it exists and I know the (unique) name of it but I don't know the extension before hand.
How can I open the file for reading?
Use glob to find it:
import os
import glob
filename = glob.glob(os.path.join(folder, name + '.*'))[0]
Or with a generator:
filename = next(glob.iglob(os.path.join(folder, name + '.*')))

Python searching directory, list basename of file, no extension

I was wondering if there was anyway I could modify my code to only post the basename of the file, instead of the entire file including the extension.. I'm new to python, so I don't know much, and I don't want to modify something and have it completely break.
import glob
import os
os.chdir( "C:/headers" )
txt = open( 'C:/files.txt', 'w' )
for file in glob.glob( "*.h" ):
with open( file ) as f:
contents = f.read()
if 'struct' in contents:
txt.write( "%s\n"%file )
txt.close()
Basically, what it does is search through a directory of header files, and if it has the struct string in the file, it'll print the files in a txt file. However, when I run it, the txt file opens with all the files listed, but I want it to only list the basename of the file, I don't need the .h at the end of it.
Please help, thank you!
root, ext = os.path.splitext(file)
name = os.path.basename(root)
root will contain the entire path of the given file name up to where the period would be before the extension, name will only be the name of the file without the leading path.
Perhaps this will help:
import glob
import os
import re
os.chdir( "C:/headers" )
txt = open( 'C:/files.txt', 'w' )
for file in glob.glob( "*.h" ):
with open( file ) as f:
contents = f.read() [...]
if 'struct' in contents:
txt.write( "%s\n"% re.sub('\.h$', '', file) )
txt.close()
Good luck!
Simply in one line..., returns the found files without any file extension, for the files found in the given search directory with the requested file extension...!
Found_BaseFile_Names= [(f.split('.'))[0] for f in os.listdir(SearchDir) if f.endswith('.txt')]

Categories

Resources