How to change file path in python - python

How would I edit the path of a file I created with file.open in python? For example, with my code:
import sys
import os
import os.path
GENPASS = ["g","q"]
FILENAME = "Test.txt"
ACC = "Test"
FILE = open(FILENAME,'a')
FILE.write(ACC)
FILE.write(','.join(GENPASS)+"/n")
How would I change the path of "FILE"

To change the path of FILE you will have to set it up in this declaration:
e.g.
FILENAME = "/mypath/Test.txt"

Related

how to set the path to the file correctly so that anyone can use it:

import pathlib
from pathlib import Path
#
dir_path = pathlib.Path.cwd()
file2 = open(dir_path, "bakf.txt", 'w')
dir_path = pathlib.Path.cwd()
file2 = open(dir_path, "bakf.txt", 'w')
I tried using the absolute path, but the username on the other PC will be different, so I'm trying via pathlib

Why isn't this working? I tried to use move in shutil in multiple ways, but none of them seem to work. What can I do?

import os
import shutil
dir_src = (r"C:\Users\Razer Blade\Desktop\src")
dir_dst = (r"C:\Users\Razer Blade\Desktop\destination")
for file in dir_src:
if file.endswith('.txt'):
shutil.move(os.path.join(file, dir_src), os.path.join(file, dir_dst))
You are not iterating over the files. Try something like this:
import glob
import os
dir_src = (r"C:\Users\Razer Blade\Desktop\src")
dir_dst = (r"C:\Users\Razer Blade\Desktop\destination")
path = os.path.join(dir_src, "*.txt")
files = glob.glob(path)
for file in files:
#do something with the file
pass

no such file of directory 'file.xml'

Having a small issues when trying to create a zip file using the zipfile module in python 3.
I have a directory which contains xml files, I am looking to create a zip archive from all these files in the same directory but keep encountering the error of FileNotFoundError: [Errno 2] no such file or directory: 'file.xml'
script:
import datetime
import os
import zipfile
path = '/Users/xxxx/reports/xxxx/monthly'
month = datetime.datetime.now().strftime('%G'+'-'+'%B')
zf = os.path.join(path, '{}.zip'.format(month))
z = zipfile.ZipFile(zf, 'w')
for i in os.listdir(path):
if i.endswith('.xml'):
z.write(i)
z.close()
it seems like when z.write(i) is called it is looking in the working directory for the xml files however the working directory is /Users/xxxx/scripts where the python script is.
How would I get the z.write(i) to look at the path variable without changing the current working directory if possible.
What actually happens is that as you loop through os.listdir(path), the i itself is simply the FileName which does not include the real Path to the File. There are a couple of ways to get around this; the simplest (but crudest) of which is shown below:
import datetime
import os
import zipfile
path = '/Users/xxxx/reports/xxxx/monthly'
month = datetime.datetime.now().strftime('%G'+'-'+'%B')
zf = os.path.join(path, '{}.zip'.format(month))
z = zipfile.ZipFile(zf, 'w')
for i in os.listdir(path):
# DECLARE A VARIABLE TO HOLD THE FULL PATH TO THE FILE:
xmlFile = "{}/{}".format(path, i) # <== PATH TO CURRENT FILE UNDER CURSOR
if xmlFile.endswith('.xml'):
z.write(xmlFile)
z.write(filename=xmlFile, arcname="ARCHIVE_NAME_HERE", ) # <== CHANGE
z.close()
Hope this Helps.
Cheers and Good-Luck...
use os.chdir to move to the file path and try to write the files to zip.
import datetime
import os
import zipfile
path = '/Users/xxxx/reports/xxxx/monthly'
month = datetime.datetime.now().strftime('%G'+'-'+'%B')
zf = os.path.join(path, '{}.zip'.format(month))
z = zipfile.ZipFile(zf, 'w')
os.chdir(path) #Change DIR
for i in os.listdir(path):
if i.endswith('.xml'):
z.write(i)
z.close()
Without changing DIR:
z = zipfile.ZipFile(zf, 'w')
for i in os.listdir(path):
if i.endswith('.xml'):
z.write(os.path.join(path, i))
z.close()

multiple .doc to .docx file conversion using python

I want to convert all the .doc files from a particular folder to .docx file.
I tried using the following code,
import subprocess
import os
for filename in os.listdir(os.getcwd()):
if filename.endswith('.doc'):
print filename
subprocess.call(['soffice', '--headless', '--convert-to', 'docx', filename])
But it gives me an error:
OSError: [Errno 2] No such file or directory
Here is a solution that worked for me. The other solutions proposed did not work on my Windows 10 machine using Python 3.
from glob import glob
import re
import os
import win32com.client as win32
from win32com.client import constants
# Create list of paths to .doc files
paths = glob('C:\\path\\to\\doc\\files\\**\\*.doc', recursive=True)
def save_as_docx(path):
# Opening MS Word
word = win32.gencache.EnsureDispatch('Word.Application')
doc = word.Documents.Open(path)
doc.Activate ()
# Rename path with .docx
new_file_abs = os.path.abspath(path)
new_file_abs = re.sub(r'\.\w+$', '.docx', new_file_abs)
# Save and Close
word.ActiveDocument.SaveAs(
new_file_abs, FileFormat=constants.wdFormatXMLDocument
)
doc.Close(False)
for path in paths:
save_as_docx(path)
I prefer to use the glob module for tasks like that. Put this in a file doc2docx.py. To make it executable, set chmod +x. And optionally put that file in your $PATH as well, to make it available "everywhere".
#!/usr/bin/env python
import glob
import subprocess
for doc in glob.iglob("*.doc"):
subprocess.call(['soffice', '--headless', '--convert-to', 'docx', doc])
Though ideally you'd leave the expansion to the shell itself, and call doc2docx.py with the files as arguments, like doc2docx.py *.doc:
#!/usr/bin/env python
import subprocess
import sys
if len(sys.argv) < 2:
sys.stderr.write("SYNOPSIS: %s file1 [file2] ...\n"%sys.argv[0])
for doc in sys.argv[1:]:
subprocess.call(['soffice', '--headless', '--convert-to', 'docx', doc])
As requested by #pyd, to output to a target directory myoutputdir use:
#!/usr/bin/env python
import subprocess
import sys
if len(sys.argv) < 2:
sys.stderr.write("SYNOPSIS: %s file1 [file2] ...\n"%sys.argv[0])
for doc in sys.argv[1:]:
subprocess.call(['soffice', '--headless', '--convert-to', 'docx', '--outdir', 'myoutputdir', doc])
If you don't like to rely on sub-process calls, here is the version with COM client. It is useful if you are targeting windows users without LibreOffice installed.
#!/usr/bin/env python
import glob
import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.visible = 0
for i, doc in enumerate(glob.iglob("*.doc")):
in_file = os.path.abspath(doc)
wb = word.Documents.Open(in_file)
out_file = os.path.abspath("out{}.docx".format(i))
wb.SaveAs2(out_file, FileFormat=16) # file format for docx
wb.Close()
word.Quit()
based on dshefman's code,
import re
import os
import sys
import win32com.client as win32
from win32com.client import constants
# Get path from command line argument
ABS_PATH = sys.argv[1]
def save_as_docx(path):
# Opening MS Word
word = win32.gencache.EnsureDispatch('Word.Application')
doc = word.Documents.Open(path)
doc.Activate ()
# Rename path with .docx
new_file_abs = os.path.abspath(path)
new_file_abs = re.sub(r'\.\w+$', '.docx', new_file_abs)
# Save and Close
word.ActiveDocument.SaveAs(new_file_abs, FileFormat=constants.wdFormatXMLDocument)
doc.Close(False)
def main():
source = ABS_PATH
for root, dirs, filenames in os.walk(source):
for f in filenames:
filename, file_extension = os.path.splitext(f)
if file_extension.lower() == ".doc":
file_conv = os.path.join(root, f)
save_as_docx(file_conv)
print("%s ==> %sx" %(file_conv,f))
if __name__ == "__main__":
main()
Use os.path.join to specify the correct directory.
import os, subprocess
main_dir = os.path.join('/', 'Users', 'username', 'Desktop', 'foldername')
for filename in os.listdir(main_dir):
if filename.endswith('.doc'):
print filename
subprocess.call(['soffice', '--headless', '--convert-to', 'docx', filename])

Does QFileDialog.getExistingDirectory() recognize %USERNAME%?

I 'm trying to open a directory dialog with a default directory which is written into an .ini file.
The .ini file looks like this :
defaultWorkingDirectory = "%%USERPROFILE%%\Documents\CAD\Working_Directory"
And I wrote a function in order to open the directory dialog :
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
from os.path import expanduser
import configparser
import itertools
import re
self.home = expanduser("~")
self.defaultPath = self.home + "\Documents\OptCAD\Working_Directory"
def openDirectoryDialog(self):
cfg = configparser.ConfigParser()
cfg.read_file(itertools.chain(['[global]'], open('C:\\Program Files (x86)\\CAD\\config.ini')))
print(cfg.items('global')) # It returns : [('defaultworkingdirectory', '"%USERPROFILE%\\Documents\\OptCAD\\Working_Directory"')]
cfgList = cfg.items('global')
wDirTuple = cfgList[(0)]
_, workingDir = wDirTuple
print(workingDir) # It returns : "%USERPROFILE%\Documents\OptCAD\Working_Directory"
self.directoryName = str(QFileDialog.getExistingDirectory(self, "Select Working Directory", workingDir, QFileDialog.ShowDirsOnly))
Then when I open the directory dialog the default directory is not the good directory.
You can always get the user profile path using expanduser, what is the need of %USERPROFILE%? You can store relative path in your config file in your case Documents\OptCAD\Working_Directory and then read it in the same way as you did in a variable say, relativeWorkingDir. Finally join it with the user profile like this.
workingDir = os.path.join(os.path.expanduser('~'), relativeWorkingDir)
I assume what you're trying to do is read values from the config file of program that you don't control.
The %USERPROFILE% syntax is windows-specific way of referring to environment variables. It won't be automatically exapnded by either Python or Qt, so you have to do it yourself:
import os
userprofile = os.environ.get('USERPROFILE')
workingdir = cfg.get('global', 'defaultworkingdirectory', fallback=None)
if workingdir and userprofile:
workingdir = workingdir.replace('%USERPROFILE%', userprofile)
else:
workingdir = os.exanduser('~\Documents\OptCAD\Working_Directory')

Categories