'File path' use causing program exit in Python 3 - windows

I have downloaded a set of html files and saved the file paths which I saved them to in a .txt file. It has each path on a new line. I wanted to look at the first file in the list and then itterate through the whole list, opening the files and extracting data before going on to the next file.
My code works fine with a single path put in directly (for the first file) as:
path = r'C:\path\to\file.html'
and works if I itterate through the text file using:
file_list_fp = r'C:\path\to\file_with_pathlist.txt'
with open(file_list_fp, 'r') as file_list:
for filepath in file_list:
pathend = filepath.find('\n')
path = file[:pathend]
q = open(path, 'r').read()
but it fails when I try getting a single path using either:
with open(file_list_fp, 'r') as file_list:
path_n = file_list.readline()
end = path_n.find('\n')
path_bad1 = path_n[:end]
or:
with open(file_list_fp, 'r') as file_list:
path_bad2 = file_list.readline().split('\n')[0]
With these two my code exits just after that point. I can't figure out why. Any pointers very welcome. (I'm using Python 3.3.1 on windows.)

Related

Python: Opening auto-generated file

As part of my larger program, I want to create a logfile with the current time & date as part of the title. I can create it as follows:
malwareLog = open(datetime.datetime.now().strftime("%Y%m%d - %H.%M " + pcName + " Malware scan log.txt"), "w+")
Now, my app is going to call a number of other functions, so I'll need to open the file, write some output to it and close the file, several times. It doesn't seem to work if I simply go:
malwareLog.open(malwareLog, "a+")
or similar. So how should I open a dynamically created txt file that I don't know the actual filename for...?
When you create malwareLog object, it has name attribute which contains the file name.
Here's an example: (my test is your malwareLog)
import random
test = open(str(random.randint(0,999999))+".txt", "w+")
test.write("hello ")
test.close()
test = open(test.name, "a+")
test.write("world!")
test.close()
with open(test.name, "r") as f: print(f.read())
You also can store the file name in a variable before or after creating the file.
###Before
file_name = "123"
malwareLog = open(file_name, "w")
###After
malwareLog = open(random.randint(0,999999), "w")
file_name = malwareLog.name

How do I access uigetfile elements via a loop?

I have to perform the following steps on set of images via matlab GUI:
Read multiple images from directory
Process them (Apply imadjust on each image)
Store them in user specified or same directory while renaming them
Can someone kindly provide me the code for the same? I am stuck after this:
[filename, pathname,~] = uigetfile( ...
{'*.jpg;*.jpeg;',...
'JPEG Files (*.jpg,*.jpeg)';
'*.png', 'PNG files (*.png)'; ...
'*.bmp','BMP File (*.bmp)'; ...
'*.tiff;*.tif','TIFF Files (*.tiff,*.tif)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick a file',...
'Multiselect','on');
set(handles.inputpathtext,'String',pathname);
[file_name_list, pathname] = uigetfile({'your filter spec','Multiselect','on');
The line above should give you a cell array containing the names of the files you selected. The following code loops through the cell array, read image, perform some adjustement, and save them with 'processed_' prefix added to the file name in the same folder specified by pathname.
for ii = 1:length(file_name_list)
if iscell(file_name_list)
filename = file_name_list{ii};
else
filename = file_name_list;
end
img = imread(fullfile(pathname, filename));
img = imadjust(img); % Do something to the image
imwrite(img, fullfile(pathname, ['processed_', filename])
end

tkinter asksaveas not saving data

Hi all and Merry Christmas!
I have a text entry widget and a save as button to save the contents of the text box to a .txt file. But when run, nothing is being saved. Can anyone tell me what I've missed...?
def file_saveAs():
from tkFileDialog import asksaveasfilename
contents = inputText.get(1.0, "end-1c")
save_file = asksaveasfilename(defaultextension = ".txt", initialdir = r"\\some\file\path\here")
line = []
for line in contents:
line = line.strip()
with open(save_file, "w") as outputFile:
outputFile.write(line)
It appears to me that it's the 'for line in contents' line where the problem lies. If I change the bottom line to 'output.write(contents)', then it saves the contents correctly, but I need to filter the contents based on a couple of other factors, so need the 'for line in' part.
Many thanks,
Chris.
change the for statement to:
for line in contents.split("\n"):
You need to split the contents into a list of lines before iterating over them.
You also need to move the with open ... statement outside the loop:
with open(save_file, "w") as outputfile:
for line in contents.split("\n"):
outputfile.write(line+"\n")

Import Multiple Images With Unknown Names

I need to import multiple images (10.000) in Matlab (2013b) from a subdirectory of the predefined directory of Matlab.
I don't know the exact names of the images.
I tried this:
file = dir('C:\Users\user\Documents\MATLAB\train');
NF = length(file);
for k = 1 : NF
img = imread(fullfile('C:\Users\user\Documents\MATLAB\train', file(k).name));
end
But it throws this error though I ran it with the Admin privileges:
Error using imread (line 347)
Can't open file "C:\Users\user\Documents\MATLAB\train\." for reading;
you may not have read permission.
The "dir" command returns the virtual directory elements "." (self directory) and ".." parent, as your error message shows.
A simple fix is to use a more specific dir call, based on your image types, perhaps:
file = dir('C:\Users\user\Documents\MATLAB\train\*.jpg');
Check the output of dir. The first two "files" are . and .., which is similar to the behaviour of the windows dir command.
file = dir('C:\Users\user\Documents\MATLAB\train');
NF = length(file);
for k = 3 : NF
img = imread(fullfile('C:\Users\user\Documents\MATLAB\train', file(k).name));
end
In R2013b you would have to do
file = dir('C:\Users\user\Documents\MATLAB\train\*.jpg');
If you have R2014b with the Computer Vision System Toolbox then you can use imageSet:
images = imageSet('C:\Users\user\Documents\MATLAB\train\');
This will create an object containing paths to all image files in the train directory, regardless of format. Then you can read the i-th image like this:
im = read(images, i);

Cannot open file for output (Matlab)

I am having a problem in matlab and the problem is described as follows:
When i try to read an image ( I have several images) and write them to a specific folder, the matlab triggers an error saying
Error using ==> imwrite at 394
Can't open file "\Temp\\inim735282.4716703009300000.jpg" for writing.
You may not have write permission.
May I know why this is happening?
this is the code where the problem occurs
mkdir('.\Temp');
temp_name = sprintf('%.16f',now);
corner_file = ['\Temp\corners', temp_name,'.in'];
image_file = ['\Temp\inim', temp_name,'.jpg'];
out_file = ['\Temp\out', temp_name,'.desc'];
out_imname = ['\Temp\out', temp_name,'.desc.jpg'];
I tried to change it by omitting
mkdir('.\Temp');
moreoever, i direct the path in the folder to the folder by doing this
binary_path = 'C:\Users\cool\Documents\MATLAB\Experment\experiments\bag_of_words\Temp';
to read and and write in and out of the folder.
Can someone please help me figure out this problem?
Thank you guys
Open MatLAB with admin privileges.
A few suggestions:
To generate a temporary output name use the command tempname.
temp_name = tempname();
To concatenate paths and file names use fullfile.
conrner_file = fullfile( '\', 'Temp', 'corners', [temp_name, '.in'] );
You should be careful not to mix '\Temp' and '.\Temp': as the first is an absolute path, while the second is a relative path to cwd.
EDIT:
How about:
temp_name = tempname(); % temp name + folder name in TEMP
corner_file = [ temp_name,'.in'];
image_file = [ temp_name,'.jpg'];
out_file = [temp_name,'.desc'];
out_imname = [temp_name,'.desc.jpg'];
Is it working now?

Resources