How can I append just just the path? - python

I want to add the path of several txt files.
This is my output: "<_io.TextIOWrapper name='(path to txt file)' mode='r' encoding='cp1252'>"
I just need the path, not the mode or encoding.
import os
from os import listdir
from os.path import isfile, join
from config import cred
import mmap
path = (r"mypath")
dirfiles = []
for filename in os.listdir(path):
with open(os.path.join(path, filename)) as f:
try:
dirfiles.append(f)
print(dirfiles)
except:
pass
Thanks in advance :D

If you are just trying to print the path
for filename in os.listdir(path):
print(os.path.join(path, filename))

Related

Python script to merge PDF files with a blank page

I have the following script compiled from other's suggestions, but I can't seem to get it to run properly. I need to merge several 3 page bill files into a single file for printing while adding a blank page in between each bill file so that each bill prints properly (we don't want the first page of one bill printed on the back of the previous bill).
# If the file errors with "no module PyPDF2" then from command line, run pip install PyPDF2
import os
from os import listdir, mkdir, startfile
from os.path import isfile, join, exists
from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter
#Input file path and print the pdf files in that path
path = input("Enter the folder location: ")
pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and '.pdf' in f]
print('\nList of PDF Files:\n')
for file in pdffiles:
print(file)
def add_blank_to_end(pdffiles: list) -> list:
names = []
for f in pdffiles:
pdf_in = open(f, 'rb')
pdf_file = PdfFileReader(pdf_in)
output = PdfFileWriter()
output.appendPagesFromReader(pdf_file)
output.addBlankPage()
names.append(f'b{f}')
outputStream = open(f'b{f}', 'wb')
output.write(outputStream)
return names
#Append the pdf files
def merge_pdfs(pdffiles: list):
merger = PdfFileMerger()
for f in pdffiles:
merger.append(f)
merger.write("document-output.pdf")
with_blank = add_blank_to_end(pdffiles)
merge_pdfs(with_blank)
# If the file errors with "no module PyPDF2" then from command line, run pip install PyPDF2
import os
from os import listdir, mkdir, startfile
from os.path import isfile, join, exists
from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter
#Input file path and print the pdf files in that path
path = input("Enter the folder location")
pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and '.pdf' in f]
print('\nList of PDF Files:\n')
for file in pdffiles:
print(file)
def add_blank_to_end(pdffiles: list) -> list:
names = []
for f in pdffiles:
pdf_in = open(path+'/'+f, 'rb')
pdf_file = PdfFileReader(pdf_in)
output = PdfFileWriter()
output.appendPagesFromReader(pdf_file)
output.addBlankPage()
names.append(f'b{f}')
outputStream = open(f'b{f}', 'wb')
output.write(outputStream)
return names
def merge_pdfs(pdffiles: list):
merger = PdfFileMerger()
for f in pdffiles:
merger.append(f)
merger.write("document-output.pdf")
with_blank = add_blank_to_end(pdffiles)
merge_pdfs(with_blank)

Recursively unzipping a folder with ZipFile/Python

I am trying to write a script which can unzip something like this:
Great grandfather.zip
Grandfather.zip
Father.zip
Child.txt
What I have so far:
from os import listdir
import os
from zipfile import ZipFile, is_zipfile
#Current Directory
mypath = '.'
def extractor(path):
for file in listdir(path):
if(is_zipfile(file)):
print(file)
with ZipFile(file,'r') as zipObj:
path = os.path.splitext(file)[0]
zipObj.extractall(path)
extractor(path)
extractor(mypath)
I can unzip great grandfather and when I call the extractor again with grandfather as path. It doesn't go inside the if statement. Even though, I can list the contents of grandfather.
Replace extractor(path) by these two lines:
os.chdir(path)
extractor('.')
So your code becomes:
from os import listdir
import os
from zipfile import ZipFile, is_zipfile
#Current Directory
mypath = '.'
def extractor(path):
for file in listdir(path):
if(is_zipfile(file)):
print(file)
with ZipFile(file,'r') as zipObj:
path = os.path.splitext(file)[0]
zipObj.extractall(path)
os.chdir(path)
extractor('.')
extractor(mypath)

python find file type and save path and name to txt/csv [duplicate]

This question already has answers here:
Python Glob without the whole path - only the filename
(10 answers)
Closed 4 months ago.
Can anyone help write a script, the goal is to find files with extension and save the name and path in TXT or CSV
that a script which find and print file file type and path,but how can i save the result to csv/txt ?
import fnmatch
import os
import csv
rootPath = '/'
pattern = '*.exe'
filepath = 'C:/Users/user/Desktop/filetest.txt'
for root, dirs, files in os.walk(rootPath):
for filepath in fnmatch.filter(files, pattern):
x = (os.path.join(root, filepath))
print(x)
i try this one, but its save only the last line.
import fnmatch
import os
import csv
rootPath = '/'
pattern = '*.exe'
filepath = 'C:/Users/user/Desktop/filetest.txt'
for root, dirs, files in os.walk(rootPath):
for filepath in fnmatch.filter(files, pattern):
x = (os.path.join(root, filepath))
file = open(filepath, 'w')
file.write(x)
file.close()
print(x)
I think the reason is you always open the file within loop using open(filepath, 'w') the option 'w' is always overwrite the file, if you want to append, you can use 'a', but I think in this case is not good solution because the main reason is you always reopen the file for each loop
By using your code, I think you can solve it by putting the open command outside the loop
import fnmatch
import os
import csv
rootPath = '/'
pattern = '*.exe'
filepath = 'C:/Users/user/Desktop/filetest.txt'
file = open(filepath, 'w')
for root, dirs, files in os.walk(rootPath):
for filepath in fnmatch.filter(files, pattern):
x = (os.path.join(root, filepath))
file.write(x+'\n')
file.close()
from glob import glob
import os
files = sorted(glob(os.path.join(rootPath, pattern)))
with open(filepath, 'w') as fid:
fid.write('\n'.join(files))

Rename the files' names

I'd like to change the files whose extension are '.test.txt' into '.txt'.
As my codes as below, it cannot work cause invalid syntax happened to the place of 'if'.
Could you please figure out it?
Thank you so much.
import sys
import os
path = "Dir"
for(dirpath,dirnames,files)in os.walk(path):
for filename in files:
filepath = os.path.join(dirpath,filename)
if '.test.txt' in filename:
newfilename = filename.replace('.test.txt','.txt')
os.rename(filename,newfilename)
this should work...
import sys
import os
path = r"Dir"
for dirpath,dirnames,files in os.walk(path):
for filename in files:
filepath = os.path.join(dirpath,filename)
if '.test.txt' in filename:
newfilename = filename.replace('.test.txt','.txt')
newfilepath = os.path.join(dirpath, newfilename)
os.rename(filepath, newfilepath)
you did not define the new file path, in renaming action you have to supply the full file path, os.rename(src_path, dest_path)

Counting "something" in multiple text files in one folder

I am trying to count the number times "Tmp" occurs in a file and what file the count belongs to. I created a script that works but I have to setup the input file and output directory for each file. To improve it I would like the script to go through each file in a folder after setting it up once.
I have been experimenting with:
import tkFileDialog
import glob
import os
directory = tkFileDialog.askdirectory()
for infile in glob.glob(os.path.join(directory, "*.*")):
open(infile, "r").read()
infile.count("Tmp")
Currently I am counting the number of times "Tmp" occurs in the file name and not the actual file, when I type:
print infile
it outputs the contents of the text files but not the directory? I am just confused on where to go or what to do.
I would use os.walk rather than glob:
import tkFileDialog
import os
import os.path
import re
directory = tkFileDialog.askdirectory()
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
path = os.path.join(dirpath, filename)
with open(path) as file:
contents = file.read()
print path[:30], contents.count('Tmp'), re.findall('Tmp\d{5}', contents)
That should be:
data = open(infile, 'r').read()
print data.count('Tmp')
import os
import glob
import tkFileDialog
directory = tkFileDialog.askdirectory()
for infile in glob.glob(os.path.join(directory, '*')):
if os.path.isfile(infile):
f = open(infile)
print os.path.split(infile)[-1], f.read().count('Tmp')

Categories

Resources