Menu
  • HOME
  • TAGS

How to set the filename encoding globally for a python interpreter?

python,encoding,utf-8,filenames

Assuming this is really what you meant (and not the encoding of the file's contents), this would do it: open = lambda fname, *a, **kw: __builtins__.open(fname.encode('utf-8'), *a, **kw) This will only affect modules that include (or import) the redefinition, so it's reasonably safe. But it might be less confusing, and...

How do I get the name of Postscript file object?

filenames,postscript

Ghostscript has a .filename operator that'll do it. No idea about the portability. Tiny viewable example: /Times-Roman findfont 12 scalefont setfont newpath 100 200 moveto currentfile .filename pop show ...

php include chinese filename

php,include,filenames

Handling non-ASCII filenames is very tricky in PHP, as it entirely delegates to the underlying filesystem. How exactly that filename is stored in the filesystem itself depends on your system and may differ widely between different systems. The short answer is: you need to match the encoding of the underlying...

how to replace special characters in file names [closed]

powershell,batch-file,replace,filenames

Coincidentally, \ / : * ? " < > | aren't allowed in Windows filenames either, so most of your list is already a non-issue. Assuming that list of characters is complete, all that remain are hashes, percents, and leading tildes. @echo off setlocal :: replace ~ only if first...

What is the .hinc Extension on a file?

html,filenames,frontend

.hinc is an included HTML source file in c++. See this link http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3325.html#style.hinc

PHP - Find File in Directory By File Name [closed]

php,select,directory,filenames

There are many ways you can do it. The simplest in this case is glob: $files = glob('/path/to/file_*.data'); print_r($files); ...

Change the file name Alfresco

workflow,filenames,alfresco,business-process

I am find own solution this issue. Need to create execution listener in user task. Its code is: <extensionElements> <activiti:executionListener class="org.alfresco.repo.workflow.activiti.listener.ScriptExecutionListener" event="start"> <activiti:field name="script"> <activiti:string><![CDATA[ if (typeof execution.getVariableLocal('zvernennya_registrationnumber') != undefined) execution.setVariable('zvernennya_registrationnumber', execution.getVariableLocal('zvernennya_registrationnumber')); if (typeof...

Log4net rolling filenames [duplicate]

c#,log4net,filenames

Add the preserveLogFileNameExtension option to your config: <preserveLogFileNameExtension value="true" /> ...

Python, pygame - Loading image filename from string variable in a list?

python,string,list,pygame,filenames

Just replace " in pet[0] with an empty string. pet.append(pygame.image.load('//home/me/Desktop/Python/'+pet[0].replace('"', "")+'.png') Example: >>> animals = {'dog': '"Dog" 4 "Bone"', 'cat': '"Cat" 4 "Yarn"', 'parrot': '"Parrot" 2 "Bell"'} >>> pet = animals['dog'].split() >>> '//home/me/Desktop/Python/'+pet[0].replace('"', "")+'.png' '//home/me/Desktop/Python/Dog.png' ...

In PHP, find an existing file using a regex pattern for the file name

php,regex,filenames

Here's one way to do it based on your exemples. I'm assuming that your checksum is of fixed length so you can just remove the (10+length of extension)th last chars of the filename and make the comparison. <?php function asset_name($start, $ext) { $dir = 'assets'; $files = glob($dir.'/*.'.$ext); $suffixLength =...

Using file-name as parameter in batch file

batch-file,filenames,rename,batch-processing,multiple-files

FOR %%A IN ("Drawings\*.txt") DO draw.exe /f "%%A" /d "%%~nA" ? Here's an excerpt from FOR help: In addition, substitution of FOR variable references has been enhanced You can now use the following optional syntax: %~I - expands %I removing any surrounding quotes (") %~fI - expands %I to a...

Calling a variable in Matlab without using the full name? [closed]

matlab,variables,filenames

Sure, you can use fieldnames to get a list of names, do your matching, then grab the field you want: f = fieldnames(Data01); match = regexp(f, '^SubData.*'); fieldnum = find(~cellfun(@isempty, match)); subdata = Data01.(f{fieldnum}); If the confusion is at the top level rather than at the substruct level, you can...

Batch-Script: Replace every “@” in file name with “_” in network drive including subfolders

batch-file,replace,folder,filenames

setsyntax for replacing a string: set "var1=my old hat" set "var2=%var1:old=new%" echo %var1% was better than %var2% To get all txt-files: for %%i in (*.txt) do ( echo %%i rem substitution does not work with special %%i variable type set "oldname=%%i" set "newname=!oldname:@=_!" echo rename "!oldname!" "!newname!" ) Why !...

Giving a string variable as a filename in matlab

string,matlab,filenames

You would need to change your back slashes \ to forward slashes /, otherwise some \ followed by a letter may be commands in the sprintffunction, like for example \N or \a. See sprintf documentation in the formatSpecarea for more information. original_image=imread(sprintf('D:/Academics/New folder/CUB_200_2011/images/%s', C{1}{2*(image_count)})); ...

Android replaces certain characters in the filename with ASCII hex value

android,filenames

new File("/sdcard/{file name}.xml").createNewFile() successfully creates a file with name "{file name}.xml" on SD card in my case. new File(context.getFilesDir() + "/{file name}.xml").createNewFile() successfully creates such file in private app files area. I checked that all right using ADB shell and file explorer....

Filename and File Globbing

linux,bash,match,filenames,globbing

You can copy from dir1 to dir2 each file that exists between 0 - 29108273357520896 fairly easily: #!/bin/bash declare -i maxval=29108273357520896 function usage { cat >&2 << TAG Copy all files from 'srcdir' to 'tgtdir' with numeric names less than 'maxname'. Usage: "${0//*\//}" srcdir tgtdir [maxname] (maxname default: $maxval) TAG...

Downloading file matching pattern using phpseclib

php,filenames,sftp,phpseclib

You have to retrieve a list of all files in the remote directory using Net_SFTP::nlist. Then you iterate the list, finding a file name that matches your requirements. Then you download the selected file using Net_SFTP::get. include("Net/SFTP.php"); $sftp = new Net_SFTP("host"); if (!$sftp->login("username", "password")) { die("Cannot connect"); } $path =...

How to capture a photo and immediately put it into an existing pdf?

android,filenames,image-capture

Override your onActivitResult() method in your Main Activity Here you will get the image bitmap from (Intent Data) public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap mImageBitmap = (Bitmap) extras.get("data"); } } Now you have the bitmap. You can...

How to get filename and location of file that starts a visual basic application?

vb.net,filenames,parent

If you've properly set up your file association, there's no need to muck around with process names. (Besides, the process starting your app would be Windows Explorer, because it's what handles double-clicks on a file and launches the associated app, so getting the process name wouldn't help you.) The filename...

std::cin working for small number of lines, but not larger ones

c++,list,import,filenames,cin

I never figured out why, but I think there is a limit to the number of characters Xcode could import for some reason (somewhere around 1000 characters). I switched over to Visual Studio on a PC and everything worked out perfectly......

How to read files in C# in a directory whose names contain a specific word? [closed]

c#,directory,filenames

Do a Directory.GetFiles(@"c:\test","*updated*"); instead of Directory.GetFiles(@"c:\test","*updated.txt");. This will help you. P.S: I'm posting this as an answer because I couldn't comment. ...

How to get file name of directory and written in button or label?

vb.net,directory,filenames

You can use the System.IO.Path class and it's method GetFileNameWithoutExtension. Dim sampleImgPath = "C:\Images\Liga BBVA.jpg" Dim nameOnly = Path.GetFileNameWithoutExtension(sampleImgPath) ' Liga BBVA How can i get the directory name of a given directory-path? Then you need to use System.IO.Path.GetDirectoryName....

Python- creating a text file with a variable as a name

python,text-files,filenames

Replace this line: with open( 'Green Bottles.txt', 'w') as a: With with open(numbers[num1] + ' Green Bottles.txt', 'w') as a: This will prepend your file name with the appropriate word....

Bash filename autocompletion after switch/parameter

bash,autocomplete,filenames

complete has a -o default option so you can remove the opts="ls *"; if ... fi part and just do complete -F _tracker -o default tracker. According to bash manual: If the -o default option was supplied to complete when the compspec was defined, readline's default completion will be performed...

Automating MS Updates with Powershell

powershell,text,extract,filenames

This should suffice for what you are looking for. $KBUpdatenames = get-childitem $folder -recurse -Filter "*.msu" | Select-Object -Expand Name $KBNumberonly = $KBUpdatenames | ForEach-Object{$_.split("-")[1]} Use Get-ChildItem to get the files of type ".msu". Using -Filter is more efficient than Where-Object in most case where you are just looking for...

Find filenames using variables in a for loop in UNIX

for-loop,awk,find,sh,filenames

Not related to your problem but a general comment. You don't need ls in those awk lines. echo will work just fine (as will awk ... <<<"$A"). Your problem is that your pattern matches too loosely. Your second to last * consumes up to the 00.0000.... bit in your first...

BASH find file names but skip a list of file names

bash,printf,sh,filenames

How about : find . $(printf "! -name %s " $(cat exclude_list_file)) -exec process {} \; ...

Why the names of some css, js files have random numbers in them?

html,web,filenames

This is normally to break caches stored by the browser so that the latest version of a file is loaded. Every time a file is changed this value will normally be changed also. This can be done manually by changing the filename and/or the paths in other files referencing this...

Android coding best practices [closed]

java,android,optimization,filenames

In AOSP ids normally use underscores. address_id instead of addressId. I have seen attributes use camelCase in AOSP however. That is the best practice. This is from the Code Style Guidelines for Contributors for AOSP: Follow Field Naming Conventions Non-public, non-static field names start with m. Static field names...

Renaming files like 20141207_190822.jpg to “2014-12-07 19.08.22.jpg” in linux or MacOS X

linux,osx,filenames

Try doing this : $ rename '[email protected]^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})@$1-$2-$3 [email protected]' * There are other tools with the same name which may or may not be able to do this, so be careful. If you run the following command : $ file $(readlink -f $(type -p rename)) and you have a result like...

PHP - get all filenames in dir by pattern

php,file,laravel,directory,filenames

glob is very much what you want here. However, being as you appear to be using Laravel (due to the tag), you should look at Laravel's FileSystem class (accessible using the File facade): 4.2 docs. It provides a wrapper for the standard PHP file functions (though doesn't actually add anything...

Echo first three characters of filenames in CMD Windows

windows,cmd,filenames

@ECHO OFF SETLOCAL :: first way: FOR /r %%g IN (*.html) DO ( SET "var=%%~ng" CALL ECHO %%var:~0,3%% ) pause :: second way: SETLOCAL ENABLEDELAYEDEXPANSION FOR /r %%g IN (*.html) DO ( SET "var=%%~ng" ECHO !var:~0,3! ) GOTO :EOF The fundamental issue is that substringing must be applied to an...

Read filename with * shell bash

linux,bash,shell,variables,filenames

Shell expansions don't happen on scalar assignments, so in varname=foo* the expansion of "$varname" will literally be "foo*". It's more confusing when you consider that echo $varname (or in your case basename $varname; either way without the double quotes) will cause the expansion itself to be treated as a glob,...

Java - Getting file name without extension from a folder

java,filenames

This code will do the work of removing the extension and printing name of file: public static void main(String[] args) { String path = "C:\\Users\\abc\\some"; File folder = new File(path); File[] files = folder.listFiles(); String fileName; int lastPeriodPos; for (int i = 0; i < files.length; i++) { if (files[i].isFile())...

Why PHP cant find long filenames?

php,filenames

Windows in particular has a very short file name limit in its original Win32 API. This general problem is discussed here at SO. At most about 260 characters can be used in an absolute path on Win32. On other platforms there are other limits, but at least 512 characters is...

Using findstr to pass to a variable

regex,batch-file,filenames,batch-processing,findstr

As I commented above, findstr (or find) will let you scrape lines containing <Name> from a text file, and for /f "delims=<>" will let you split those lines into substrings. With findstr /n, you're looking for "tokens=3 delims=<>" to get the string between <Name> and </Name>. Try this: @echo off...

Visual Studio c++ how to add version info read from .rc or .h to targetname?

c++,properties,visual-studio-2013,build,filenames

You can use Property Macros. So if you were to bring up Property Manager (View > Property Manager) and right-click a configuration and choose Add New Property Sheet... then edit that property sheet by right-clicking on it and choosing properties. Then under Common Properties and then User Macros make a...

Beginner Python: save output file as argv input filename

python,filenames,argv

Get input file name by the sys.argv Use same name with different extension to save result. Simple example to get input file name and use same file name to save output. e.g. import sys if __name__=="__main__": print "argument:", sys.argv inputfile = sys.argv[1] print "inputfile:", inputfile outputfile = inputfile.split(".")[0] +...

awk to manipulate multiple files

awk,output,line,filenames

$ awk -v RS= -F'\n' -v OFS=' | ' '{$1 = FILENAME OFS $1}1' file1.txt file2.txt file1.txt | SERVICE: 1 | TASK: 1 | RESULT: 1 | ADDITIONAL: 1 file1.txt | SERVICE: 2 | TASK: 2 | RESULT: 2 | ADDITIONAL: 2 file1.txt | SERVICE: 3 | TASK: 3 |...

Insert into a cell the first five characters of the filename

excel,excel-formula,cell,filenames,worksheet-function

Please try: =MID(CELL("filename"),FIND("[",CELL("filename"))+1,5) . @barry houdini has kindly pointed out that the above is flawed (in a way that may not often be an issue but could at times be very confusing): It's better to use a cell reference in CELL function with this formula, e.g. =MID(CELL("filename",A1),FIND("[",CELL("filename",A1))+1,5) - that ensures...

Exception handling, only accept specific file inputs

python,input,types,exception-handling,filenames

If you want to keep asking until the user enters a filename with the correct extension using str.endswith: def fileName(): while True: filename = raw_input("Please enter .txt or .csv file: ") if filename.endswith((".csv",".txt")) return filename else: print("Extension must be .csv or .txt") If you actually want to just verify the...

How do I escape spaces in a path with Applescript?

path,escaping,applescript,filenames,space

You can use the text item delimiters to find and replace characters tell application "Finder" to set sel to POSIX path of (the selection as alias) set the clipboard to "afp://myserver._afpovertcp._tcp.local/" & (my findReplace(text 10 thru -1 of sel, " ", "%20")) on findReplace(t, toFind, toReplace) set {tid, text item...

Saving multiple files with same name

c#,wpf,unique,filenames

In your original code, you do the check only once. Try (note the while): filename = "C:\\test.csv"; int count = 0; while (File.Exists(filename)) { count++; filename = "C:\\test" + count + ".csv"; } //save file goes here If you prefer, you can replace the while with this for loop: for(int...

Safe to use random numbers to make filenames unique?

c#,unique,filenames

I just wanted to know if using this method to generate unique filenames is a good idea? No. Uniqueness isn't a property of randomness. Random means that the resulting value is not in any way dependent upon previous state. Which means repeats are possible. You could get the same...

DateValue and Format in a single formula

excel,vba,date,format,filenames

Try this: Dim RefDate As Date RefDate = Range("J2").Value NameofFile = "On Time Departure " & Format(RefDate, "m-d-yy") EDIT If J2 contains a string and not a date, like Christmas007 noted, try this: Dim curDate As String Dim RefDate As Date curDate = Range("J2").Value RefDate = DateValue(Left(curDate, InStr(curDate, " ")))...

Python 3 not aware of Windows filename encodings?

windows,python-3.x,encoding,path,filenames

eryksun answered my question in a comment. I copy his answer here so the thread does'nt stand as unanswered, The win-unicode-console module solved the problem: Python 3's raw FileIO class forces binary mode, which precludes using a UTF-16 text mode for the Windows console. Thus the default setup is limited...

Convert list of paths to list of filenames

windows,string,batch-file,filenames

The following will put each file name on a separate line within the clipboard: @(for %%F in (%*) do @echo %%~nxF)|clip If you prefer, the following will put a space delimited list of file names on a single line, with quotes around each file name. @(for %%F in (%*) do...

VBA – print file name in each row until the file closes

excel,vba,excel-vba,filenames

Since you already have a way of figuring out the last used row at a time, you are very close to a solution. What you want to do is to write the objFile.Name not only to StartSht.Cells(i, 1), but to StartSht.Range(StartSht.Cells(i, 1), StartSht.Cells(GetLastRowInColumn(StartSht, 3), 1)). To break it down: StartSht.Range()...

Filename from string(path) without file exist

c#,string,filenames

You can use the Path methods even if the file doesn't exist. Actually those Path methods are just string methods. So this works: string fileName = System.IO.Path.GetFileName(@"C:\cSharp\test\001.txt"); //001.txt ...

space containing items in bash for-loop

bash,for-loop,whitespace,filenames,filepath

This will do the job: #!/bin/bash ############################################################################# function do_recursive_pandoc { local src_path=$(realpath "$1") local output_path=$(realpath "$2") && mkdir --parents "$output_path" 2>/dev/null find "$src_path" -name "*.markdown" -not -path "$output_path" -exec bash -c ' i=$1 o="$3""${1#$2}" mkdir --parents "$(dirname "$o")" 2>/dev/null if [ -f "$i" ]; then pandoc -rmarkdown -whtml "$i" --output="$o".html...

Issue creating .txt file with long name

python,filenames

if you are working with files in windows, colon (:) is an invalid character in a filename.

Remove leading and tailing whitespaces from filename

linux,bash,shell,unix,filenames

This should do: shopt -s extglob while IFS= read -r -d '' f; do d=${f%/*} b=${f##*/*([[:space:]])} b=${b%%+([[:space:]])} echo mv -v -- "$f" "$d/$b" done < <( find -depth \( -name '[[:space:]]*' -o -name '*[[:space:]]' \) -print0 ) As written, it won't do anything, it'll only echo the mv that will...

Allow dots in filenames while searching for extension using pathinfo

php,filenames,glob

You want DirectoryIterator class from SPL. http://php.net/manual/en/class.directoryiterator.php This is just a sample you can do with it, but you can customize a lot what you get out from it: array ( 0 => '/var/www/html/UusProjekt/intl/homepage_template.php', 1 => '/var/www/html/UusProjekt/intl/config.php', 2 => '/var/www/html/UusProjekt/intl/english.php', 3 => '/var/www/html/UusProjekt/intl/spanish.php', 4 => '/var/www/html/UusProjekt/intl/index.php', ) ...

PHP absolute file

php,filenames,glob,filesize

$sz = 0; $dir = '/tmp'; // will find largest for `/tmp` if ($handle = opendir($dir)) { // will iterate through $dir while (false !== ($entry = readdir($handle))) { if(($curr = filesize($dir . '/' . $entry)) > $sz) { // found larger! $sz = $curr; $name = $entry; } }...

How do I distinguish between a file and a folder when renaming a file/folder in java

java,folder,filenames,rename,lastindexof

You can use someFile.isDirectory(); It returns true if the file is a folder, and false if not....

Alternative to colon in a time format

filenames,iso8601

There is none. ISO 8601 only allows for a colon (:) for separating time components in the extended format: The basic format is [hh][mm][ss] and the extended format is [hh]:[mm]:[ss]. There is no provision for an alternate extended format....

Copy file1 name inplace of file2 and add extra to it, but not copy file1 extention

java,file,copy,filenames,rename

How i understand your problem this is how i think the solution could look like (java 7+) public class FileConverter { public static void main(String[] args) throws IOException { FileConverter converter = new FileConverter(); File newFile1 = new File("c:/parent1/file1.dump"); File newFile2 = new File("c:/parent2/file2.dump"); converter.convert2Files(newFile1, newFile2); } private void convert2Files(File...

Randomly select image an from directory using php and use its filename for a mysql query

php,mysql,random,filenames

If the file info in your db is update-to-date regarding the image files in your file system, you can get the 5 random filename ids along with other info directly from the db: $sql = 'SELECT * FROM image_files ORDER BY RAND() LIMIT 5'; This will return you file ids...

VB6 get filename from path

csv,path,vb6,filenames

Function GetFileNameFromPath(strFullPath As String) As String GetFileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "\")) End Function However, your problem is caused by either you not using FreeFile or not closing the file and it is locked. Public Function SomeMethod() On Error GoTo errSomeMethod Dim lngFileHandle As Long lngFileHandle = FreeFile Open...

Cross check files in two folders

vbscript,match,filenames

It's rather unsurprising that you don't know what went wrong when you tell your script to shut up about whatever's going wrong (On Error Resume Next). Remove that line (using global OERN is a terrible practice anyway) and see what error you get. Most likely the error is "permission denied",...

Remove Last Characters from my filenames in windows

windows,batch-file,filenames,rename

With your recent clarification - I would do the following. @echo off setlocal enabledelayedexpansion set FOLDER_PATH=C:\Some\Path\ for %%f in (%FOLDER_PATH%*) do if %%f neq %~nx0 ( set "filename=%%~nf" ren "%%f" "!filename:~0,-4!%%~xf" ) PAUSE This will change your examples 10_myfile_12345_6789.txt 11_myfile_12345_0987.txt Into 10_myfile_12345_.txt 11_myfile_12345_.txt If you want to remove the trailing...

Python: how to obtain only first filename in the directory

python,path,filenames

os.walk os.walk(top, topdown=True, onerror=None, followlinks=False) Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). ... Example dirs structure $ tree -d . └──...

how can I cat two files with a matching string in the filename?

python,python-2.7,filenames,cat

Here's a solution in Python (it will work unchanged with both Python 2 and 3). This assumes that each file XXXXX.fasta has one and only one matching XXXXX.fasta stringofstuff file. import glob fastafiles = sorted(glob.glob("*.fasta")) for fastafile in fastafiles: number = fastafile.split(".")[0] space_file = glob.glob(number + ".fasta *") with open(fastafile,...

VBA Save As Current Filename +01

vba,excel-vba,iteration,filenames,save-as

Put this out to a couple of my friends and below is their solution: Sub Copy_DailySheet() Dim datestr As String, f As String, CurrentFileDate As String, _ CurrentVersion As String, SaveAsDate As String, SaveAsVersion As String f = ThisWorkbook.FullName SaveAsDate = Format(Now, "yyyymmdd") ary = Split(f, "_") bry = Split(ary(UBound(ary)),...

bash, list filenames, array

arrays,bash,for-loop,filenames

Try this: sYear=2011 sMonth=03 eYear=2013 eMonth=08 shopt -s nullglob declare -a files for year in *; do (( ${year} < ${sYear} || ${year} > ${eYear} )) && continue for year_month in ${year}/*; do month=${year_month##*/} (( ${year} == ${sYear} && ${month##0} < ${sMonth##0} )) && continue; (( ${year} == ${eYear} &&...

Volt compiled filenames can get very long and fail creation on Windows

windows,filenames,phalcon,volt

A NFR has been created for this #3226, to be addressed after 2.0 is released. However there is an easy workaround as @Andres offers You can currently use a closure to generate this kind of file: $volt->setOptions( [ 'compiledPath' => function($templatePath) { return md5($templatePath) . '.php'; } ] ); ...

Probability of already existing file System.IO.Path.GetRandomFileName()

c#,.net,file,random,filenames

Internally, GetRandomFileName uses RNGCryptoServiceProvider to generate 11-character (name:8+ext:3) string. The string represents a base-32 encoded number, so the total number of possible strings is 3211 or 255. Assuming uniform distribution, the chances of making a duplicate are about 2-55, or 1 in 36 quadrillion. That's pretty low: for comparison, your...

Powershell file and directory names as strings, sans decorations

string,powershell,filenames

A few quick ways, all using the Split-Path cmdlet which is perfect for this: $foo= ls foo.txt | select FullName $bar = Split-Path $foo.fullname Or: $foo= ls foo.txt | select -ExpandProperty FullName $bar = Split-Path $foo Or even shorter: $bar = Split-Path (gci foo.txt).fullname ...

python compare and replace strings in txt file with filenames

python,list,replace,compare,filenames

import os with open("data.txt") as infile: for line in infile: line = line.strip() if os.path.isfile(os.path.join("sounds", line)): os.rename(os.path.join("sounds", line), os.path.join("sounds", os.path.splitext(line)[0] + '.wav')) ...

mysqldump with date and time in backup file name on windows

windows,cmd,filenames,mysqldump

You can not have : as a part of the file name on Windows. Try the following batch file, it will create file with the name in the format such as: backup_3.2.2.6__2015-06-02_17-50-44.sql: @echo off for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I set datetime=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2%_%datetime:~8,2%-%datetime:~10,2%-%datetime:~12,2%...

How to Combine Two paths?

c#,xml,path,filenames

You have a two different problems that you need to solve separately. Depending on the API used to consume the image file, a file:// URI path may or may not be supported. So you'd want to make that a local path as explained in Convert file path to a file...

Using basename to name output file in java

java,find,xslt-1.0,filenames,zsh

Here's a zsh approach, since it's tagged it as such. for f in **/*.foo(.); print -- java ... -o $f:r.bar $f Remove the print -- when you're satisfied that it looks good. The (.) says files only. The :r says remove the .foo extension. It's helpful to remember the path...

AppleSctipt Finding File with partial filename

get,applescript,filenames

This is best done with shell script. Use "do shell script" if you must do it in AppleScript. You can concatenate the string part of do shell script with whatever you want, for example: set file_start to "file_start" set file_ext to ".txt" do shell script "mdfind -name " & quoted...

regex for preg_replace: seperate path and filename

php,regex,preg-replace,filenames,filepath

This should work: (https?:\/\/.+\/)(.+). An example is available here. That being said, you should see if it is possible to combine this approach with a DOM parse so that you can extract the property you need first....

writing to variable filename

c++,filenames,fstream,ofstream

You forgot to call myfile.close() at the end of the loop. It will be easier if you define myfile in the scope of the for loop. for(unsigned int i = 0; i<sizeof(rvalues)/sizeof(rvalues[0]);i++){ r = rvalues[i]; x = x0; y = y0; z=z0; stringstream ss; cout<<"ravlues = "<<r<<endl; ss<<"r="<<r<<".txt"; string filename...

Sort list of strings with starting number in powershell

sorting,powershell,filenames

Here is one way to do it: $test = @('1. First', '2. Second', '11. Eleventh') $sort = @() foreach($item in $test){ $item -match '^(\d+).*' $temp = New-Object PSCustomObject -property @{'Number' = [int]$matches[1]} $sort += $temp } $sort | Sort-Object Number | Select-Object Data ...

Read applications in Folder in Java

java,osx,filenames

OS X Applications are folders, not files. They are special folders that end in a '.app' extension and contain a special sub-directory structure. So by using file.isFile() you are effectively filtering the applications out. Do this to list the applications: for (File file : listOfFiles) { if (file.isDirectory()) { System.out.println(file.getName());...

How to get just a File Name from the full path?

c#,file,file-io,classpath,filenames

You can use Path.GetFileName Method in Path Class: string fileName = @"C:\mydir\myfile.ext"; string path = @"C:\mydir\"; string result; result = Path.GetFileName(fileName); Console.WriteLine("GetFileName('{0}') returns '{1}'", fileName, result); result = Path.GetFileName(path); Console.WriteLine("GetFileName('{0}') returns '{1}'", path, result); // This code produces output similar to the following: // // GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext' // GetFileName('C:\mydir\')...

How to rename several filenames all stored in a single file

unix,filenames,edit

sed -i -e 's;^;/Users/Desktop/TIMIT_wav/;' file_with_filenames.txt Which will make substitution (s/from/to/) of the beginning of line (^) with desired path (/Users/Desktop/TIMIT_wav/)....

Using Apple automator to delete portion of filename before file extension

osx,filenames,rename,automator

Can you make sure you don't have a file with the same name as the one being renamed?

Automating filename generation from url text

python,filenames,python-requests

You can use BeautifulSoup to get the title text from the page, I would let requests handle the encoding with .content: url = "http://rads.stackoverflow.com/amzn/click/1593271840" html = requests.get(url).content from bs4 import BeautifulSoup print(BeautifulSoup(html).title.text) with open("{}.html".format(BeautifulSoup(html).title.text), "wb") as file: file.write(html) The Google Way: How One Company is Revolutionizing Management As We Know...

VBA Excel: Make header depend on filename

excel,vba,excel-vba,header,filenames

The code doesn't include Filename declaration and assignment, but if it's a string then you should replace: If Filename.Contains("W") Then With If Filename Like "*W*" Then You can also simplify the logic in your if statement, and get rid of GoTo: With ActiveSheet.PageSetup If Filename Like "*W*" Then .LeftHeader =...

Find digits in file names and cross reference them with others

c++,regex,string,filenames

For me (gcc4.6.2 32-bit optimizations O3), manual string manipulation was about 2x faster than regular expressions. Not worth the cost. Example runnable complete code (link with boost_system and boost_regex, or change include if you have regex in the compiler already): #include <ctime> #include <cctype> #include <algorithm> #include <string> #include <iostream>...

pathnames in Common Lisp, filenames with wildcards in them

common-lisp,filenames,wildcard,clisp,pathname

It depends on the implementation, but for some, a backslash does in fact work. But because namestrings are strings, to get a string with a backslash in it, you have to escape the backslash with another backslash. So, for example, "foo?" is escaped as "foo\\?", not "foo\?". Last time I...

from x(defined in program) import y(defined in program) python

python,python-2.7,import,filenames

You can't use a variable for an import statement. from x import y will try to find a module literally called y. In your case, that probably means you want a file in the same directory called y.py. It will then try to find a variable (including, eg, a function...

PHP - Windows - filename incorrect after upload (ü saved as ü etc.)

php,windows,encoding,filenames

In the end I solved it with the following approach: When uploading the files I urlencode the names with rawurlencode() When fetching the files from server they are obviously URL encoded so I use urldecode($filename) to print correct names Links in a href are automatically translated, so for example "%20"...

Getting NoneType Error When Using Regex to Change Filenames in Python

python,regex,filenames

You are passing bare file names to os.rename, probably with missing paths. Consider the following layout: yourscript.py subdir/ - one - two This is similar to your code: import os for fn in os.listdir('subdir'): print(fn) os.rename(fn, fn + '_moved') and it throws an exception (somewhat nicer in Python 3): FileNotFoundError:...

Fortran: Enter a file name and read the array

arrays,fortran,filenames,define

You are attempting to open the file called "filename" no matter what the user enters. This line: open(12,file='filename') should be: open(12,file=filename) With quotes it is the string literal "filename", without quotes it is the contents of the variable named filename. You will also need to declare the variable filename with...

Remove-Item with “.” in filenames doesn't work

powershell,filenames

Ending a folder name with a dot is not allowed in windows: Do not end a file or directory name with a space or a period. Although the underlying file system may support such names, the Windows shell and user interface does not. However, it is acceptable to specify a...

Simple ZSH function and files with spaces in their name

whitespace,filenames,zsh,expansion

The shell performs parameter substitution and word-splitting in this order. This means you eventually execute vim /home/username/Dropbox/20150209-132501-Recx-new note today.md.md I.e. you call vim with three file names. If you want to suppress word-splitting on the substituted part, you must use quotes in the function definition as well: function note() {...

Get current filename PHP [duplicate]

php,file,filenames

Use: basename($_SERVER['SCRIPT_FILENAME']) Reference...

Applescript for changing filenames

automation,applescript,filenames,rename,finder

Just use the space as the delimiter and build the parts. Edited: to allow for spaces in the text parts. tell application "Finder" to set aList to every file in folder "ImageRename" set AppleScript's text item delimiters to " " repeat with i from 1 to number of items in...

Copy certain files from one folder to another using python

python,file,csv,filenames

Given the name of the file columns['label'] you can use the following to move a file srcpath = os.path.join(src, columns['label']) dstpath = os.path.join(dst, columns['label']) shutil.copyfile(srcpath, dstpath) ...

Tail command - follow by name on Solaris

filenames,solaris,file-descriptor,tail

According to the GNU tail manual, --follows is the same as -f: -f, --follow[={name|descriptor}] output appended data as the file grows; an absent option argument means 'descriptor' A -f option is found in the POSIX description of tail. However, the --follows option (which accepts an option value) is not in...