The aim of this code is to select a file then add it to a table and in the next column it should display the file format. Example:
[File Name] [File Format]
[candy.csv] [a csv file]
[corona.txt] [a txt file]
[computer.json] [a json file]
I know how to select files and i know how to create a table, but I am having trouble to make the two work together. I am new to python.
This is the code to select all the files in a specific folder
def browse():
os.chdir("/home/amel/Downloads/Corona")
for file in glob.glob("*.*"):
s = file
print(s)
folder_path = str(s)
tx.insert(END, folder_path + '\n')
return s
Try using os module to split pathfilename into components.
Taking your code snippet and expanding it to include a key binding <Control-g> that calls function browse.
This splits pathfilename into path, filename and then filename into name, ext.
filename and ext are inserted into tk.Text to produce an appropriate list.
import tkinter as tk
import os, glob
root = tk.Tk()
tx = tk.Text()
tx.grid()
# select your own path
pathname = os.getcwd()
def browse(ev):
os.chdir(pathname)
for file in glob.glob("*.*"):
path, filename = os.path.split(file)
name, ext = os.path.splitext(filename)
tx.insert(tk.END, f"[{filename}] [{ext}]\n")
root.bind("<Control-g>", browse)
root.mainloop()
Related
I'm trying to copy files from directory A, to directory B, based on a txt file containing the list of files to be extracted - located in directory B. I referred to this code: How to extract files from a particular folder with filename stored in a python list?
but it doesn't seem to enter the if (where I have put the 'in here' printout). Could someone tell me what I am doing wrong?
This is the code:
import os
import shutil
def read_input_file():
my_file = open("/mnt/d/Downloads/TSU/remaining_files_noUSD_19Jan.txt", "r")
# reading the file
data = my_file.read()
data_into_list = data.split("\n")
#print(data_into_list)
my_file.close()
return data_into_list
def filter_data(list_of_files):
path="/mnt/e/Toyota Smarthome/Untrimmed/Videos_mp4"
path_to_be_moved="/mnt/d/Downloads/TSU"
#print(list_of_files)
for file in os.listdir(path):
#print(file)
if file in list_of_files:
print("in here")
print(file)
shutil.copytree(path,path_to_be_moved)
#os.system("mv "+path+file+" "+path_to_be_moved)
if __name__ == "__main__":
list = read_input_file()
filter_data(list)
I am using python3 via WSL.
the mp4 folder contains multiple videos, and the output of "
read input file
is as follows
"
Thank you!
I think copytree from shutil has another purpose to just move file, it moves an entire structure. I'd use shutil.move
import os
import shutil
def read_input_file():
my_file = open("list.txt", "r")
data = my_file.read()
data_into_list = data.split("\n")
my_file.close()
return data_into_list
def filter_data(list_of_files):
path="directoryA/"
path_to_be_moved="directoryB/"
for file in os.listdir(path):
# print(file)
if file in list_of_files:
print("in here")
print(file)
shutil.move(path+file,path_to_be_moved+file)
mylist = read_input_file()
filter_data(mylist)
just saw your update, be careful, data_into_list = data.split("\n") is for a file.txt with a list separated with an enter. yours is with a comma and space so you'll have to change that.
Also you shouldn't use list as a variable name, mylist for example is better. list() is used to create list
So I've been working on this for quite a while now..
The incoming mail (paper) is scanned using a Xerox WorkCentre.
On the screen we select the matching scan folder for any customer/vendor (4 digit number).
So any invoice by vendor x is stored in a specific folder.
Now we'd like to rename the pdf-file by prepending the matching customer-ID (4 digits) to the file, which happens to be the name of the parent folder where the pdf is stored in.
On our server we have a folder structure where all the scans are stored like this:
S:/Scan/[4 digit number]/filename.pdf
e.g. S:/Scan/9020/
where the contents is like
doc_12345.pdf
doc_12346.pdf
[...]
Now I'd like to prepend the parent folder name to any file like this:
S:/Scan/9020/doc_12345.pdf becomes S:/Scan/9020/9020_doc_12345.pdf
S:/Scan/9021/doc_12346.pdf becomes S:/Scan/9021/9021_doc_12345.pdf
After the file has been renamed, it should be moved to a common folder like:
S:/Scan/Renamed/
I would appreciate any ideas :)
Try this:
import os
import glob
import pathlib
inp_dir = 'S:/Scan/'
out_dir = 'S:/Scan/Renamed/'
folder_list = [i for i in pathlib.Path(inp_dir).iterdir() if i.is_dir()]
for cust in folder_list:
flist = glob.glob(str(cust) + '/*.pdf')
flist = [pathlib.Path(i) for i in flist]
for file in flist:
new_name = f'{cust.name}_{file.name}'
os.rename(str(file), f'{out_dir}{new_name}')
import os
import shutil
source = 'S:/Scan/Source/'
target = 'S:/Scan/Renamed/'
for dpath, dnames, fnames in os.walk(source):
for f in fnames:
n = dpath.rsplit('/',2) [-1]
os.chdir(dpath)
if not f.startswith(n):
os.rename(f, f.replace(f, n+'_'+f))
nf = dpath+"/"+n+'_'+f
shutil.move(nf, target)
That's what I've got so far.
Seems to work.
Example of PDF: "Smith#00$Consolidated_Performance.pdf"
The goal is to add a bookmark to page 1 of each PDF based on the filename.
(Bookmark name in example would be "Consolidated Performance")
import os
from openpyxl import load_workbook
from PyPDF2 import PdfFileMerger
cdir = "Directory of PDF" # Current directory
pdfcdir = [filename for filename in os.listdir(cdir) if filename.endswith(".pdf")]
def addbookmark(f):
output = PdfFileMerger()
name = os.path.splitext(os.path.basename(f))[0] # Split filename from .pdf extension
dp = name.index("$") + 1 # Find position of $ sign
bookmarkname = name[dp:].replace("_", " ") # replace underscores with spaces
output.addBookmark(bookmarkname, 0, parent=None) # Add bookmark
output.append(open(f, 'rb'))
output.write(open(f, 'wb'))
for f in pdfcdir:
addbookmark(f)
The UDF works fine when applied to individual PDFs, but it won't add the bookmarks when put into the loop at the bottom of the code. Any ideas on how to make the UDF loop through all PDFs within pdfcdir?
I'm pretty sure that the issue you're having has nothing to do with the loop. Rather, you're passing just the filenames and not including the directory path. It's trying to open these files in the script's current working directory (the directory the script is in, by default) rather than in the directory you read the filenames from.
So, join the directory name with each file name when calling your function.
for f in pdfcdir:
addbookmark(os.path.join(cdir, f))
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