i create a python file via the "with open()" method and now i would like to import the file but the filename should be variable.
filename = "Test"
with open(filename + ".py", "w+") as file:
file.write("def main():\n\tpass")
Now at a other line in the skript i would like to import the python script called like filename. But you cant do something like:
import filename
because then python searches for a python script called "filename". but in this example it should import "Test.py". Any suggestions?
You want the built in import function
new_module = __import__(modulename)
so...
filename = "Test"
with open(filename + ".py", "w+") as file:
file.write("def main():\n\tpass")
new_module = __import__(filename)
Visit https://docs.python.org/3/library/functions.html#__import__
Related
f = open("demofile3.txt", "w")
f.writelines(["\nSee you soon!", "\nOver and out."])
f.close()
`
I have been trying to create or open a file and write something in it but it does not seem to do anything.
it's about pwd.
But here is a method: use full path.
For example:
from pathlib import Path
folder = Path(__file__).parent
your_txt = folder / "demofile3.txt"
with open(your_txt, "w") as f:
f.writelines(["\nSee you soon!", "\nOver and out."])
I have made a piece of code to automate making a new project. I ahve mangaged to create the file in a location I like, create the file and create a test python file. How would I open that file in vs code?
import subprocess,os,time
projectName = input("What is the name of the project?\n")
filename = "test"
fileEx = '.py'
os.chdir('../')
os.chdir('../')
os.chdir('../')
os.chdir('.\Documents\ ')
os.chdir('.\programs\ ')
project = subprocess.Popen(["powershell","md",projectName])
file = filename + fileEx
fileLoctaion = os.getcwd() + file
d = os.getcwd() + f'\{projectName}\ '
time.sleep(1)
os.chdir(d)
with open(file, 'w') as fp:
pass
You could try the following:
import os
os.system("code NAMEOFFILE.py") ## the "code" command is the command used to open a file with vsc in a command line interface.
You can do the same thing with subprocess:
import subprocess
subprocess.getoutput("code NAMEOFFILE.py")
I am not a python expert but I am using it.
What I have is a list of CDF files from which I want to extract a global attribute (which is of type CDF_DOUBLE) and write this variable into a single binary file. I am using pycdf for it.
I am able to extract the global attribute, but I am not able to write it into the binary file.
Here is the code:
#!/usr/bin/env python3
import os
import zipfile
from spacepy import pycdf
input_path = '/home/mypath'
filelist = os.listdir(input_path)
for filename in filelist:
fullfilename = input_path + '/' + filename
zfile = zipfile.ZipFile(fullfilename, 'r')
cdffile_zip = zfile.extract(zfile.namelist()[0], '/home/scratch/')
cdffile = pycdf.CDF(cdffile_zip)
zfile.close()
glob_attr = cdffile.attrs['MY_GLOBAL_ATTR']
with open('somefile.bin', 'wb') as f:
f.write(glob_attr) <-- ***PROBLEM HERE***
f.close()
command = 'rm -f {}'.format(cdffile_zip)
os.system(command)
Thanks for any help
i have this python script that open a file dialog and select a text file than copy its content to another file.
when i open the second file it still empty
can anyone help me to solve this problem ?
OPenDirectory.py
#!/usr/bin/python
import Tkinter
import tkFileDialog
''''Open txt files in the selected path '''
def OpenRead():
Tkinter.Tk().withdraw()
in_path = tkFileDialog.askopenfile(initialdir = 'C:\Users\LT GM\Downloads', filetypes=[('text files', ' TXT ')])
readingFile = in_path.read()
writeFile = open ('copiedFile.txt', 'w')
writeFile.write(readingFile)
print " we'r done!!"
in_path.close()
writeFile.close()
if __name__== "__main__":
OpenRead()
You can use shutil.copyfile, there is no need to open or read the file.
from shutil import copyfile
copyfile("source","dest")
So for your code:
def OpenRead():
Tkinter.Tk().withdraw()
in_path = tkFileDialog.askopenfile(initialdir = 'C:\Users\LT GM\Downloads', filetypes=[('text files', ' TXT ')])
copyfile(in_path.name, 'copiedFile.txt')
print " we'r done!!"
if __name__== "__main__":
OpenRead()
The file is also going to be copied to you pwd so if you want it save somewhere in particular you need to pass the full path.
Line by line way of copying from file to file:
#!/usr/bin/python
from os import listdir
from os.path import isfile, join
def readWrite():
mypath = 'D:\\'
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in files:
if file.split('.')[1] == 'txt':
outputFileName = 'out-' + file
with open(mypath+outputFileName, 'w') as w:
with open(mypath+file) as f:
for l in f:
print l
w.write(l)
if __name__== "__main__":
readWrite()
UPDATE:
updated the code above, so it reads all the txt files in a specified directory and copies them into other files. You can play with directories how you like. I also added a "print l" which will print the contents of the incoming file.
readingFile = in_path.read()
reads the contents of the file and puts it in variable readingFile
suppose the contents of the file is,say, hello the value of readingFile will be hello
destinationFile = readingFile, '.txt'
destinationFile is a tuple with values '<'contents of file'>','.txt'
instead use destinationFile = readingFile+'.txt'
this will work. but the end result would not be what you are expecting.the result would be a file with name as contents of the reading file with contents also the same. better specify a file name in destinationFile like destinationFile = 'destfile.txt'
Why don't you just use os, and the shell copy command.
import os
start= '~/user/file'
dest= '~/user/folder1/file'
os.system('cp %s %s' %(start,dest))
I would like to save the output in the same location as the input but using a different, but still related, name.
Minimal Example:
This script searches for lines containing the string "NFS" in the input file. Then, it prints the results to another file.
I would like to save the print result to an output file in the same location as the input file but using a different name like "inputfilename.out.csv".
Here is the code :
from __future__ import print_function
import sys
fname = sys.argv[1]
out = open(fname.out.csv, "w") #this doesn't work but this is the idea
with open(fname) as file:
reader = file.readlines()
for line in reader:
if "NFS" in line:
print(line, file = out)
Any suggestions ?
You could use os.path.splitext() to extract extension:
import os
name, ext = os.path.splitext(fname)
output_filename = name + ".out" + ext
Or if you want to change the name completely, you could use os.path.dirname() to get the parent directory:
import os
dirpath = os.path.dirname(fname)
output_filename = os.path.join(dirpath, "outputfile.txt")
Use concatenation to add ".out.csv" to the end of your string.
out = open(fname + ".out.csv", "w")
If the input filename is "inputfilename", then the output will be "inputfilename.out.csv". This may be undesirable behavior if the input filename already has an extension. Then "inputfilename.csv" will become "inputfilename.csv.out.csv". In which case, you may wish to use os.path to construct the new name.
import os.path
filename = "inputfilename.csv"
root, extension = os.path.splitext(filename)
output_filename = root + ".out" + extension
print output_filename
Result:
inputfilename.out.csv