I have the python script below to iterate over all files ending with 'mkv', and print the same string without the 'mkv' at the end.
But, instead it prints the original filename including the 'mkv', why??
files=os.system('find /media/radamand/230_GB -name *mkv')
for file in str(files):
converted_filename=file[0:-3]
print(converted_filename)
Your os.system call executes your find command, sends its output to your interpreter standard output stream (which is why you're seeing your matching files including the "mkv" at the end, as this output is not the result of your print function in your later code), and then simply returns the exit code.
So your files variable actually gets an assignment of the integer 0.
Your for loop then casts files from an int into a string ('0') and thus your for loop now actually means: "loop through each character of the string files" (there is only one however), which, in this case, due to your slicing of [:-3] on a string of only one character, evaluates as an empty string which gets passed to your print function.
So, os.system isn't designed for what you are trying to achieve.
If you potentially have other folders in the parent folder you are searching, that may also have the filenames you are looking for, then I would recommend using the glob module.
import glob
files = glob.glob("/media/radamand/230_GB/*mkv") # Returns a list of strings for matched files
for file in files:
print(file[:-3])
You can add and set the keyword arguments recursive and/or include_hidden to True if required.
If, however, you are only looking for the files in the current folder, you can use fnmatch:
import fnmatch
import os
for file in os.listdir("/media/radamand/230_GB"):
if fnmatch.fnmatch(file, "*mkv"):
print(file[:-3])
Related
I want to pause my python script while waiting for a file download to happen.
I don't want to use an explicit wait.
I want this to run fast and not rely on an explicit wait.
I'm kinda noobish but here is what I have tried.
file_check = glob.glob1('downloads', '*.pdf')
while not os.path.isfile(str(file_check)):
time.sleep(1)
I used the str() because it complained about needing a string for the path.
I have a feeling this isn't the way to properly do this. so how should I dynamically wait for a file download?
P.S
My .pdf file downloads into '/downloads', and my pdf is dynamically named before download so that's why I need globs wildcard.
When you do file_check = glob.glob1('downloads', '*.pdf') the result of glob.glob1(...) is stored in file_check just once and that's it. In this case, if you enter inside the while loop you never will get out of there because file_check will not change (except if there are threads or stuff like that that can modify their value externally).
glob.glob and glob.glob1 (this one it's not even public, as you can see the docs) returns a list. If 'downloads' folder it's empty, you will get an empty list []. In Python, lists have an implicit booleanness, so if the list it's empty, in a conditional statement it will be interpreted as False, or 'True' if it's not empty.
Rewriting your code the result will be something like this:
while not glob.glob1('downloads', '*.pdf'):
time.sleep(1)
I want to pass a string from C to Fortran and then process it line-by-line as if I was reading a file. Is this possible?
Example String - contains newlines
File description: this file contains stuff
3 Values
1 Description
2 Another description
3 More text
Then, I would like to parse the string line-by-line, like a file. Similar to this:
subroutine READ_STR(str, len)
character str(len),desc*70
read(str,'(a)') desc
read(str,*) n
do 10 i=1,n
read(str,*) parm(i)
10 continue
Not without significant "manual" intervention. There are a couple of issues:
The newline character has no special meaning in an internal file. Records in an internal file correspond to elements in an array. You would either need to first manually preprocess your character scalar into an array, or use a single READ that skipped over the newline characters.
If you did process the string into an array, then internal files do not maintain a file position between parent READ statements. You would need to manually track the current record yourself, or process the entire array with a single READ statement that accessed multiple records.
If you have variable width fields, then writing a format specification to process everything in a single READ could be problematic, though this depends on the details of the input.
I have to write a MATLAB function with the following description:
function counts = letterStatistics(filename, allowedChar, N)
This function is supposed to open a text file specified by filename and read its entire contents. The contents will be parsed such that any character that isn’t in allowedChar is removed. Finally it will return a count of all N-symbol combinations in the parsed text. This function should be stored in a file name “letterStatistics.m” and I made a list of some commands and things of how the function should be organized according to my professors' lecture notes:
Begin the function by setting the default value of N to 1 in case:
a. The user specifies a 0 or negative value of N.
b. The user doesn’t pass the argument N into the function, i.e., counts = letterStatistics(filename, allowedChar)
Using the fopen function, open the file filename for reading in text mode.
Using the function fscanf, read in all the contents of the opened file into a string variable.
I know there exists a MATLAB function to turn all letters in a string to lower case. Since my analysis will disregard case, I have to use this function on the string of text.
Parse this string variable as follows (use logical indexing or regular expressions – do not use for loops):
a. We want to remove all newline characters without this occurring:
e.g.
In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
In my younger and more vulnerableyears my father gave me some advicethat I’ve been turning over in my mindever since.
Replace all newline characters (special character \n) with a single space: ' '.
b. We will treat hyphenated words as two separate words, hence do the same for hyphens '-'.
c. Remove any character that is not in allowedChar. Hint: use regexprep with an empty string '' as an argument for replace.
d. Any sequence of two or more blank spaces should be replaced by a single blank space.
Use the provided permsRep function, to create a matrix of all possible N-symbol combinations of the symbols in allowedChar.
Using the strfind function, count all the N-symbol combinations in the parsed text into an array counts. Do not loop through each character in your parsed text as you would in a C program.
Close the opened file using fclose.
HERE IS MY QUESTION: so as you can see i have made this list of what the function is, what it should do, and using which commands (fclose etc.). the trouble is that I'm aware that closing the file involves use of 'fclose' but other than that I'm not sure how to execute #8. Same goes for the whole function creation. I have a vague idea of how to create a function using what commands but I'm unable to produce the actual code.. how should I begin? Any guidance/hints would seriously be appreciated because I'm having programmers' block and am unable to start!
I think that you are new to matlab, so the documentation may be complicated. The root of the problem is the basic understanding of file I/O (input/output) I guess. So the thing is that when you open the file using fopen, matlab returns a pointer to that file, which is generally called a file ID. When you call fclose you want matlab to understand that you want to close that file. So what you have to do is to use fclose with the correct file ID.
fid = open('test.txt');
fprintf(fid,'This is a test.\n');
fclose(fid);
fid = 0; % Optional, this will make it clear that the file is not open,
% but it is not necessary since matlab will send a not open message anyway
Regarding the function creation the syntax is something like this:
function out = myFcn(x,y)
z = x*y;
fprintf('z=%.0f\n',z); % Print value of z in the command window
out = z>0;
This is a function that checks if two numbers are positive and returns true they are. If not it returns false. This may not be the best way to do this test, but it works as example I guess.
Please comment if this is not what you want to know.
this is my first time asking a question so let me know if I am doing something wrong (post wise)
I am trying to create a function that writes into a .txt but i seem to get two very different results between calling it from within a module, and writing the same loop in the shell directly. The code is as follows:
def function(para1, para2): #para1 is a string that i am searching for within para2. para2 is a list of strings
with open("str" + para1 +".txt", 'a'. encoding = 'utf-8') as file:
#opens a file with certain naming convention
n = 0
for word in para2:
if word == para1:
file.write(para2[n-1]+'\n')
print(para2[n-1]) #intentionally included as part of debugging
n+=1
function("targetstr". targettext)
#target str is the phrase I am looking for, targettext is the tokenized text I am
#looking through. this is in the form of a list of strings, that is the output of
#another function, and has already been 'declared' as a variable
when I define this function in the shell, I get the correct words appearing. However, when i call this same function through a module(in the shell), nothing appears in the shell, and the text file shows a bunch of numbers (eg: 's93161), and no new lines.
I have even gone to the extent of including a print statement right after declaration of the function in the module, and commented everything but the print statement, and yet nothing appears in the shell when I call it. However, the numbers still appear in the text file.
I am guessing that there is a problem with how I have defined the parameters or how i cam inputting the parameters when I call the function.
As a reference, here is the desired output:
‘She
Ashley
there
Kitty
Coates
‘Let
let
that
PS: Sorry if this is not very clear as I have very limited knowledge on speaking python
I have found the solution to issue. Turns out that I need to close the shell and restart everything before the compiler recognizes the changes made to the function in the module. Thanks to those who took a look at the issue, and those who tried to help.
I am trying to locate the full name of a file using a wildcard. The code I have is:
MLCNo=crjbis.ffromlot
subfolder=LEFT(mlcno,3)
filename=SYS(2000,'S:\MLC\MLC#\'+subfolder+'xx\'+mlcno+'21391*.pdf')
pathname="S:\MLC\MLC#\"+subfolder+"xx\"+filename
Pathname is passed to a print function to print the file. All of this works great if I don't use a variable in the SYS function (even with a wildcard). I should add that there will only ever be one file returned by the wildcard. Is there another way to do this?
Thanks!!!
Tammy