File Paths From Ch 10 Python Crash Course File Path Example - python-3.x

I'm trying to figure out how to use File Paths. This is the example that I am given but, it makes zero sense, I tried to copy the exact path that didn't work. I'm using Pycharm.
What I tested
file_path = 'D:\PycharmProjects\Standard_Library\pi_digits.txt'
with open(file_path) as file_object:
Book Example Below
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:

The author uses the Unix system and you are using the windows system and the only difference between the two examples is the file-separator.
In Python, you can declare separators either with hard-coded (For Unix: /, for windows: \)
But you can use os.path to remove the confusion of the os separator. Just place the text file in your current directory and you can use it in the example like below:
import os.path
text_file = 'pi_digits.txt'
file_path = os.path.join(os.getcwd(), text_file)
print(file_path)
Out:
/Users/PycharmProjects/StackOverFlow-pip/pi_digits.txt
Since I'm also using a Unix system my example is similar to the book example. But If you try it in your pc you will see similar to the below:
'D:\PycharmProjects\Standard_Library\pi_digits.txt'
Then you can open the text file and read it using with open(file_path) as file_object:

Related

How to extract .000 file type in python

How to extract them in python scripts by using shutil or somethings
import os
import shutil
directory = os.path.join(os.getcwd(), "BDP Raw data")
def extract(path,director,check):
if check:
shutil.unpack_archive(path, directory)
if check == False:
shutil.unpack_archive(path, directory,'tar')
def extractzip():
for file in os.listdir(directory):
if file.endswith('.zip'):
file_path = f"{directory}\{file}"
extract(file_path,directory,True)
for file in os.listdir(directory):
if file.startswith('9050') or file.startswith('9070'):
directory_path = f"{directory}\{file}"
for file in os.listdir(directory_path):
extractTo000 = f"{directory}\TestExtract000"
extract_path000 = f"{directory_path}\{file}"
extract(extract_path000,extractTo000,False)
extractzip()
Output should be like this method :
Then I must get this:
I'm not sure that shutil or even py7zr would be able to extract a .000 file.
One of the workarounds is to use Python's built-in module subprocess to unzip this kind of files by 7zip through the Windows command line.
1- CONFIGURATING THE VARIABLE ENVIRONNEMENT
First of all, you need to execute the command below in the command prompt to make sure that your user path environement is pointing to the .exe file of 7-zip. You can also do that manually (see this post).
set PATH=%PATH%;C:\Program Files\7-Zip\"
2- WRITING THE PYTHON FILE
Then, create a .py file in the same directory of your .000 files and write the code below :
from pathlib import Path
import subprocess
path = r'C:\Users\abokey\Desktop\000files'
for file in Path(path).glob('*.000'):
print(file)
subprocess.call(['7z', 'e', file], shell=True)
If you need to extract the files to a specific directory, add the option -o (Set Output Directory):
#make sure to change the output path
subprocess.call(['7z', 'e', file, r'-oC:\Users\abokey\Desktop\000files\output'], shell=True)
Make sure to adapt the code below to match your expectations :
from pathlib import Path
import os
import subprocess
directory = os.path.join(os.getcwd(), "BDP Raw data")
extractTo000 = directory + r'\TestExtract000'
for file in Path(directory).glob('*.000'):
if file.stem.startswith(('9050', '9070')):
subprocess.call(['7z', 'e', file, fr'-o{extractTo000}'], shell=True)
Note : Read full documentation of 7zip here.

File not found error altough file does not exist

I am trying to read through a file using the with open () function from python. I hand in the filepath via a base path and then a relative path adding on it:
filepath = base_path + path_to_specific_file
with open (filepath) as l:
do_stuff()
base_path is using the linux home symbol ( I am using Ubuntu on a VM) ~/base_path/ since I want to have the filepath adapted on every device instead of hardcoding it.
This does not work. When I execute the code, it throws a file not found error, although the path exists. I even can open it by clicking the path in the vscode terminal.
According to this thread:
File not found from Python although file exists
the problem is the ~/ instead of /home/username/. Is there a way to replace this to have it working on every device with the correct path? I cannot comment yet on this thread since I do not have enough reputation, therefore I needed to create this new question. Sorry about that.
You can use the expanduser() from pathlib for this. Example
import pathlib
filepath = pathlib.Path(base_path) / path_to_specific_file
filepath = filepath.expanduser() # expand ~
with open(filepath) as l:
do_stuff()
This should work fine.
You can join paths e.g. with:
filepath = '/'.join((basepath, path_to_specific_file))
Or do as Kris suggested: use pathlib:
>>> basepath = Path('/tmp/')
>>> path_to_specific_file = Path('test')
>>> filepath = basepath / path_to_specific_file
>>> print(filepath)
/tmp/test
EDIT:
To access $HOME (~) you can use Path.home().

Python 3.5:Not able to remove non alpha -numeric characters from file_name

i have written a python script to rename all the files present in a folder by removing all the numbers from the file name but this doesn't work .
Note :Same code works fine for python2.7
import os
def rename_files():
#(1) get file names from a folder
file_list = os.listdir(r"D:\prank")
print(file_list)
saved_path = os.getcwd()
print("Current working Directory is " + saved_path)
os.chdir(r"D:\prank")
#(2) for each file ,rename filename
for file_name in file_list:
os.rename(file_name, file_name.translate(None,"0123456789"))
rename_files()
Can anyone tell me how to make it work.Is the translate function which is not working properly
The problem is with os.rename() portion of your code.
os.rename() requires you to give it a full path to the file/folder you want to change it to, while you only gave it the file_name and not the full path.
You have to add the full path to the folders/files directory.
so it should look like this:
def rename_files():
# add the folder path
folder_path = "D:\prank\\"
file_list = os.listdir(r"D:\prank")
print(file_list)
saved_path = os.getcwd()
print("Current working Directory is " + saved_path)
os.chdir(r"D:\prank")
# Concat the folder_path with file_name to create the full path.
for file_name in file_list:
full_path = folder_path + file_name
print (full_path) # See the full path here.
os.rename(full_path, full_path.translate(None, "0123456789"))
look up the documentation for os, heres what ive found on rename:
os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file.
This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.
If you want cross-platform overwriting of the destination, use replace().
New in version 3.3: The src_dir_fd and dst_dir_fd arguments.
heres a link to the documentation, hope this helps, thanks
https://docs.python.org/3/library/os.html
Others have pointed out other issues with your code, but as to your use of translate, in Python 3.x, you need to pass a dictionary mapping ordinals to new values (or None). This code would work:
import string
...
file_name.translate(dict(ord(c), None for c in string.digits))
but this seems easier to understand:
import re
...
re.sub(r'\d', '', file_name)

File edition after glob function through python

I wanted to find every instances of a file under different directories and search for value 0 in each of those files and replace them with 500.
Please find the code below:
!/usr/bin/python
import glob
import os
a = glob.glob('/home/*/hostresolve')
for i in a:
print i
=================================
Now that I found all instances of hostresolve file under home. I wanted to search for value 0 and replace them with value 500 in each of these files. I know there is find and replace function in python but I wanted to know how can we use it to output that we got through glob.
As from [Python Docs] (https://docs.python.org/2/library/glob.html) glob.glob returns a list. In your case, its a list of matching files in the directory. hence to replace the required text in the all the files, we should iterative over the list. Accordingly the code would be
import glob
import os
a = glob.glob('/home/*/host*')
for files in a:
with open(files, 'r') as writingfile:
read_data = writingfile.read()
with open(files, 'w') as writingfile:
write_data = read_data.replace('0', '500')
writingfile.write(write_data)
Also using "with" to operate on file data is efficient, because it handles close() and flush() automatically avoiding excess code and it has been suggested in previous answers [1] (https://stackoverflow.com/a/17141572/6005652).
Further to reuse or make it more efficient, u can refer to maps (https://docs.python.org/3/library/functions.html?highlight=map#map) as the list of files is an iterable object.
From my understanding, this suffices an answer to your question.
It worked except for one thing
There are three files instances the code worked for 2 and 3 instance but first instance file remains same.
[root#localhost home]# cat /home/dir1/hostresolve
O
[root#localhost home]# cat /home/dir2/hostresolve
500
[root#localhost home]# cat /home/dir3/hostresolve
500
Please find the code below :
!/usr/bin/python
import glob
import os
a = glob.glob('/home/*/hostresolve')
for files in a:
print files
with open(files, 'r') as writingfile:
read_data = writingfile.read()
with open(files , 'w') as writingfile:
write_data = read_data.replace('0','500')
writingfile.write(write_data)
But when I print files I get all instance of the file which means for loop will process all 3 instances and also checked the permission of these files and I found that all 3 have same permissions

How to convert Balsamiq mockups to text strings txt with Python34 script on Windows XP

I've been trying to run these scripts https://github.com/balsamiq/mockups-strings-extractor within XP. I'm getting errors per this screenshot https://www.dropbox.com/s/rlbqp1iytkwvq3m/Screenshot%202014-05-30%2011.57.48.png
Also I tried CD into my test directory and although a text output file is generated it is empty and I still get these errors https://www.dropbox.com/s/odjfbr97e5i4gnn/Screenshot%202014-05-30%2012.09.31.png
Is anybody running Balsamiq on windows able to make this work ?
1) From the looks of the first error pic you included, you were trying to execute a Windows Shell command inside of a Python Interpreter. If you've still got the window open, type quit() before attempting your command again.
2) Your script was written for Python 2.x. If you're using Python 3.x, you'll need to add parentheses to the print lines in the script file and change urllib to urllib.parse. I made the changes below:
import os
import glob
import re
import urllib.parse
for infile in glob.glob( os.path.join(".", '*.bmml') ):
print("STRINGS FOUND IN " + infile)
print("===========================================================")
f = open (infile,"r")
data = f.read()
p = re.compile("<text>(.*?)</text>")
textStrings = p.findall(data)
print(urllib.parse.unquote('\n'.join(textStrings))+"\n")
f.close()
Hope this helps.

Resources