Hello I have a file named files.txt in that file there are paths to files for example:
/home/ojom/123.jpg
/home/ojom/oaksdokwijeqijwqe.jpg
There is million of those paths in this file I need to see if the files in that file are physically located (exists) on my hard drive (if they don't write those paths to another file) how do I do that? What can I use?
You could parse that file using PHP and then go through the results and check them with file_exists.
The example below works if every file path is on a new line.
<?php
$files = array();
$handle = fopen("files.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if(!file_exits($line)) {
continue; // file does not exist, skip
} else {
$files[] = $line;
}
}
} else {
die('Error opening the file');
}
fclose($handle);
echo "These files exist:";
echo "<pre>" . print_r($files, true) . "</pre>"; // prints them as an array
You could also use the array for further processing.
Here is the Python solution:
import os.path
files = 'c:\\test\\files.txt'
output = 'c:\\test\\filesNotExist.txt'
with open(files) as f:
for file in f:
if not os.path.isfile(file):
f = open(output, 'w')
f.write(file)
f.close()
f.close()
This script scans your text file and writes list of non-existed files to the output text file.
Related
I am using this script as a template to rename a file in VLC: https://github.com/surrim/vlc-delete/
The Script works as intended.
My code looks like this:
function descriptor()
return {
title = "VLC Rename";
version = "0.1";
author = "I";
shortdesc = "Rename current file";
description = [[
<h1>vlc-rename</h1>"
When you're playing a file, use VLC Rename
to rename the current file]];
}
end
function removeItem()
local id = vlc.playlist.current()
vlc.playlist.delete(id)
vlc.playlist.gotoitem(id + 1)
vlc.deactivate()
end
function activate()
local item = vlc.input.item()
local uri = item:uri()
oldFile = vlc.strings.decode_uri(string.gsub(uri, "^file:///", ""))
d = vlc.dialog( "Rename Dialog" )
d:add_label("Filename")
w = d:add_text_input(oldFile, 1, 5,200 ,30)
d:add_button("OK", click_ok)
d:show()
end
function click_ok()
local newFile = w:get_text()
vlc.msg.info("[vlc-rename] renaming: " .. oldFile .. " with " .. newFile)
if newFile ~= oldFile then
removeItem()
retval, err = os.rename(oldFile,newFile)
vlc.msg.info("[vlc-rename] end rename")
if (retval == nil) then
vlc.msg.err("[vlc-rename] fail: " .. err)
end
end
d:delete()
vlc.deactivate()
end
function deactivate()
vlc.deactivate()
end
function close()
deactivate()
end
function meta_changed()
end
This code outputs an error from the os.rename() function:
lua error: [vlc-rename] fail: [my filename] Permission denied
Regardless of elevation level.
I am using windows 10 64bit and VLC 3.03.
Since this is my first lua script I welcome any input.
I might be wrong, but maybe the file you are trying to rename is already opened elsewhere or by VLC (you said you want to rename the "current file").
Actually, the problem is, When system getting upgrade it should write "DISABLE_BACKUP" file in root directory. When it comes up, i have to check whether the file has been in root or not.
if ((dir = opendir ("/"))!=NULL)
{
while ((ent = readdir(dir)) != NULL)
{
printf ("%s\n", ent->d_name);
//Here i have to compare the filename (DISABLE_BACKUP) with the string "DISABLE_BACKUP" and has to raise log entry.
}
closedir(dir);
}
The C function for comparing strings is strcmp():
if (strcmp(ent->d_name, "DISABLE_BACKUP")==0) {
// Found it!
Perhaps a better way to see if the file "DISABLE_BACKUP" exists is access():
#include <unistd.h>
...
if (access(fname, F_OK) != -1) {
// file exists
} else {
// file doesn't exist
}
I've created a uncompress function, put together from a few code snippets and a few alterations from my side, automatically handling the file type.
My current usecase is to extract a ~550mb zip file from a SMB share on windows with a lot of files in it (qt 5.5 source code)
On Linux, this is a tgz file on a nfs share and it takes 67 seconds for the function to extract it. (other uncompression method than for zip files)
On Windows it takes >15minutes.
I'm thinking about using a system(7z $source) call as alternative.
Do you have any suggestions what's the fastest method to extract a zip file on windows?
Plz be honest, if my uncompress function is crap, i'm no perl expert... :)
Here's my code:
#uncompress full archive file $archFile to $destPath
sub uncompress
{
my $fileToExtract = shift;
my $targetPath = shift;
my $silent = shift;
my $status;
my $buff;
unless (-f $fileToExtract)
{
&error ("$fileToExtract is not a file!");
}
unless (-d $targetPath)
{
&makeDir($targetPath, 1);
}
# just look for .tar since all .tar archives with all compressions can be extracted.
if ($fileToExtract =~ m/.tar/)
{
my $pwd = getcwd();
changeDirectory($targetPath, 1);
my $tar = Archive::Tar->new();
$tar->read($fileToExtract);
$tar->extract();
changeDirectory($pwd, 1);
return;
}
elsif ($fileToExtract =~ m/.zip$/)
{
my $u = new IO::Uncompress::Unzip $fileToExtract or die "Cannot open $fileToExtract: $UnzipError";
for ($status = 1; $status > 0; $status = $u->nextStream())
{
my $header = $u->getHeaderInfo();
my (undef, $path, $name) = splitpath($header->{Name});
my (undef, $path, $name) = splitpath($header->{Name});
my $destdir = "$targetPath$path";
unless (-d $destdir)
{
&makeDir( $destdir, 1);
}
if ($name =~ m!/$!) {
last if $status < 0;
next;
}
my $destfile = "$destdir/$name";
if ($destfile =~ m/\/\/$/) # skip if no filename is given
{
next;
}
$destfile =~ s|\/\/|\/|g; # remove unnecessary doubleslashes
my $fh = openFileHandle ( $destfile , '>', 1 );
binmode($fh);
while (($status = $u->read($buff)) > 0) {
$fh->write($buff);
}
$fh->close();
unless (defined $silent)
{
&syslog ("Uncompress $destfile -> $targetPath");
}
#set timestamps of file to the ones in the zip
my $stored_time = $header->{'Time'};
utime ($stored_time, $stored_time, $destfile);
}
if ($status < 0)
{
die "Error processing $fileToExtract: $!\n"
}
}
else
{
my $ae = Archive::Extract->new( archive => $fileToExtract );
$ae->extract( to => $targetPath ) or &error("Failed to extract $fileToExtract with error $ae->error");
unless (defined $silent)
{
foreach my $file (#{$ae->files})
{
#only print if not a directory
if( $file!~m|/$| )
{
&syslog("Uncompress $fileToExtract -> $targetPath");
}
}
}
}
return;
}
You could simply do it in below manner using Archive::Extract, it provides generic archive extracting mechanism, therefore you don't have to install separate modules for tar and zip.
use Archive::Extract;
my $ae = Archive::Extract->new( archive => $fileToExtract );
my $ok = $ae->extract( to => $targetPath );
If you specifically want to check whether a file is tar or zip then you can use below:
$ae->is_tar
$ae->is_zip
Note that Archive::Extract is a core module therefore you'll not have to install it separetely.
I am not being able to read the contents of the file tutc.txt. I want to write a subroutine to read the contents of a file which will be called from the perl script.
My module is named Module.pm
package Module;
use warnings;
use strict;
use Carp;
use feature "switch";
no warnings 'experimental::smartmatch';
# Constructor and initialisation
sub new { #class method
my $class = shift; #shift without arguments is shift #_ , takes 1st element of argument array
my $self = {#_}; #created a Hash reference with #_ helping to store values in a hash
bless ($self, $class); #turning self into an object by telling which class it belongs to without hardcode name in
$self->{_created} = 1; #syntax for accessing the contemts of a hash: refrence $object_name->{property_name}.
return $self;
}
#reading from config file
sub read {
my ($self, $file) = shift;
my $self = #_;
open my $config_fh, $file or return 0;
$self->{_filename} = $file; # Store a special property containing the name of the file
my $section;
my $config_name;
my $config_val;
while (my $line = <$config_fh>)
{
chomp $line;
given ($line) {
when (/^\[(.*)\]/)
{
$section = $1;
}
when (/^(?<key>[^=]+)=(?<value>.*)/)
{
$section //= '';
$self->{"$section.$config_name"} = $config_val;
}
}
}
close $config_fh;
return $self;
}
sub fetch {
my ($self, $key) = shift;
return $self->{$key};
}
My perl file looks like the following:
#!/usr/bin/perl
use Module;
use strict;
use warnings;
my $value = Module->new();
$value->read('/Users/hhansraj/git/edgegrid-curl/tutc.txt') or die "Couldn't read config file: $!";
print "The author's first name is ",$value->fetch('author.firstname'),"\n";
My text file looks like the following:
[author]
firstname=Doug
lastname=Sheppard
[site]
name=Perl.com
url=http://www.perl.com/
In your "read" subroutine, it looks like the first two lines of code (listed below) may be the source of your problem.
my ($self, $file) = shift;
my $self = #_;
In the first line, you're removing the first element of the #_ array (arguments to the subroutine) and putting that into the $self variable. And nothing is being entered into the $file variable. In the second line, you are redeclaring the $self variable and are assigning to it the size of what's left of the #_ array. I suspect that you're code is assigning the value/data to the $self variable that you are wanting.
Since the $file variable is not getting assigned any value, that is probably creating an issue with the open function. Also, you did not specify the file mode in your attempt to open the file. To just fix the missing mode specification to specify read only mode, you can change the following line:
open my $config_fh, $file or return 0;
to be
open (my $config_fh, "<", $file) or return 0;
I'm trying to determine if one of several directories are present from within a lua script. It works on OSX, but not on Windows (linux is currently untested, but I expect that one to work). When the following code runs, I get an error:
failed with this C:\Program Files (x86)\VideoLAN\VLC\lua\playlist\: No such file or directory
I can confirm that that directory exists. I've escaped the slashes, I'm not sure what else could be the issue.
local oses = { "/Applications/VLC.app/Contents/MacOS/share/lua/playlist/"; "C:\\Program Files\\VideoLAN\\VLC\\lua\\playlist\\"; "C:\\Program Files (x86)\\VideoLAN\\VLC\\lua\\playlist\\"; "/usr/lib/vlc/lua/playlist" }
-- Determine which OS this is (and where to find share/lua).
local f,err = io.open( oses[1], "r")
if not err then
opsys = "OSX"
scriptpath = oses[1] .. script
f:close()
else
f,err = io.open( oses[2], "r")
if not err then
opsys = "Win32"
scriptpath = oses[2] .. script
f:close()
else
f,err = io.open( oses[3], "r")
vlc.msg.dbg( dhead .. 'failed with this ' .. err .. dtail )
if not err then
opsys = "Win64"
scriptpath = oses[3] .. script
f:close()
else
f,err = io.open( oses[4], "r")
if not err then
opsys = "Linux/Unix"
scriptpath = oses[4] .. script
f:close()
else
return false
end
end
end
end
The file "C:\Program Files\VideoLAN\VLC\lua\playlist\" does not exist. If you were to remove the trailing slash, you'd be trying to open a directory and probably get a permissions error. It's not going to work either way. If you're going to use this method of determining OS, you should be trying to open files.
For instance, build your script path, try to open that file, and use that to determine pass/fail.
Side note, the structure of your code could be vastly improved. Any time you have a bunch of duplicate code that differs by an index, you should be using a loop. For instance, we can replace your code with this:
local oses = {
["OSX"] = "/Applications/VLC.app/Contents/MacOS/share/lua/playlist/",
["Win32"] = "C:\\Program Files\\VideoLAN\\VLC\\lua\\playlist\\",
["Win64"] = "C:\\Program Files (x86)\\VideoLAN\\VLC\\lua\\playlist\\",
["Linux/Unix"] = "/usr/lib/vlc/lua/playlist",
}
for osname, directory in pairs(oses) do
local scriptpath = directory..script
local f,err = io.open( scriptpath, "r")
if not err then
f:close()
return scriptpath, osname
end
end