I'm scanning log files (in a directory) for specific lines, need to output all in a text file.  For some reason, I do not understand, I have an error:  NameError: name 's' is not defined   I tried to assign Var s to a different Var but still cannot get around the problem.  In my code, I going to have one "if" and 5 "elif" like this:  If    var1 elif    var2 elif    var3 elif    var4 elif    var5 elif    var6 write.output_file(var1+var2+var3+var4+var5+var6+'\n')   Here is the code:  import os import re  start_tm  = ',"  Start Time' test_ID   = ' Host Name: '  cell_f = open('C:\\03\\OUTCOME.txt','w') given_path = 'C:\\02\\en15\\TST2'   for filename in os.listdir(given_path):     filepath = os.path.join(given_path, filename)     if os.path.isfile(filepath):         #print("File Name:   ", filename)          print("File Name\\Path:", filepath+'\n')          with open(filepath) as mfile:                     for rn_l in mfile:                 rn_l= rn_l.rstrip()                  if start_tm  in rn_l:                     *extraWords,st_t1 = rn_l.split('Time') # Grtting Start Time #                     s=str(st_t1)                     s=s.replace('"','')                      print ("Start String \"s\"is a TYPE  ", type(s))                     print ("START TIME STRING "+s)                  elif test_ID  in rn_l:                                           *extraWords,t_id1,t_id2, = rn_l.split( )                                                      print ("TESTER ID ---&gt;&gt;&gt; "+t_id1)                                                            t_id11,t_id12, = rn_l.split('Host')                       *w,e,c,d = re.split(" +", t_id11)                     cell = str(e+'_'+c)                     cell = cell.replace('[','').replace(']','')                     print ("Cell Line " + cell+'\n')
2152
What exactly are the Python scoping rules?  If I have some code:  code1 class Foo:    code2    def spam.....       code3       for code4..:        code5        x()   Where is x found?  Some possible choices include the list below:   In the enclosing source file In the class namespace In the function definition In the for loop index variable Inside the for loop   Also there is the context during execution, when the function spam is passed somewhere else. And maybe  pass a bit differently?  There must be a simple reference or algorithm somewhere.  It's a confusing world for intermediate Python programmers.
75457
I am trying to populate a field with corresponding file name. For example, if the file name is Route1.shp then the field value will be Route1 as well. However my code is not working. Can you please suggest a code that works? The code I used is given below, along with the error message             import arcpy, os, sys     from arcpy import env     arcpy.env.overwriteOutput = True     env.workspace = r"C:\ABC\GIS"     fc_tables = arcpy.ListFeatureClasses ("R*")     for fc in fc_tables:         field = "RouteName"         arcpy.AddField_management (fc, field, "TEXT")     for fc in fc_tables:     arcpy.CalculateField_management (fc, field, str(fc), "PYTHON")   And this is the error message     Runtime error  Traceback (most recent call last):   File "",   line 2, in    File "c:\program   files\arcgis\desktop10.1\arcpy\arcpy\management.py", line 3128, in   CalculateField     raise e ExecuteError: ERROR 000539: Error running   expression: Route1.shp  Traceback (most recent call last):   File   "", line 1, in  NameError: name 'Route1' is not   defined  Failed to execute (CalculateField).
48268
I have some simple python code that searches files for a string e.g. path=c:\path, where the c:\path part may vary. The current code is:  def find_path(i_file):     lines = open(i_file).readlines()     for line in lines:         if line.startswith("Path="):             return # what to do here in order to get line content after "Path=" ?   What is a simple way to get the text after Path=?
62288
This question was prompted by questions about ls' -1 option and the recurring tendency of people to ask question and answers that includes processing the output of ls.   This reuse of the output ls seems understandable, e.g.: if you know how to sort a list of files with ls you might want to use the output in that way as input for something else.  If those Q&amp;A don't include a reference to the file name list produced consisting of nicely behaving file names (no special characters like spaces and newlines), they are often commented upon by someone pointing out the danger of the command sequence not working when there are files with newlines, spaces etc.  find, sort and other utilities solve the problem of communicating "difficult" file names to e.g. xargs by using an option to separate the file names with the NUL character/byte which is not a valid character in file name (the only one in addition to /?) on Unix/Linux filesystems.  I looked to the man page for ls and the output for ls --help (which has more options listed) and could not find that ls (from coreutils) has an option to specify NUL separated output. It does have a -1 option which can be interpreted as "output file names separated by newline")  Q: Is there are technical or philosophical reason why ls does not have a --zero or -0 option that would "output file names separated by NUL"?  If you do something that only outputs the file names (and not use e.g. -l) that could make sense:  ls -rt -0 | xargs -r0 …   I could be missing something why this would not work, or is there an alternative for this example that I overlooked and that is not much more complicated and/or obscure.    Addendum:  Doing ls -lrt -0 probably does not make much sense, but in the same way that find . -ls -print0 does not, so that is not a reason to not provide a -0/-z/--zero option.
40363
I'm trying to replace each , in the current file by a new line:  :%s/,/\n/g    But it inserts what looks like a ^@ instead of an actual newline. The file is not in DOS mode or anything.  What should I do?  If you are curious, like me, check the question  as well.
18131
Test environment:  $ mkdir testdir $ cd testdir $ echo | tee "file  name"   Now, ls will print file?name (under Ubuntu GNU bash, at least), while ls | cat will print file and name in separate lines.  What I'd like to achieve is, print file?name with the  piped version, so something like  $ something ls | cat` or `ls | something | cat` or `ls | something cat   In other words, how to fool a command like ls here into thinking, it has a TTY, when it does not, in the shell?  Note: ls is just an example program here, I'm looking for generic solution, not program specific like ls -q | cat would be.
77902
I have a small text file that I'd like to read into a scalar variable exactly as it is in the file (preserving line separators and other whitespace).  The equivalent in Python would be something like  buffer = ""  try:     file = open("fileName", 'rU')     try:         buffer += file.read()     finally:         file.close() except IOError:     buffer += "The file could not be opened."   This is for simply redisplaying the contents of the file on a web page, which is why my error message is going into my file buffer.
33483
Preface: Every couple of days there comes a question of this type, which is easy to solve with sed, but takes time to explain. I'm writing this question and answer, so I can later refer to this generic solution and only explain the adaption for the specific case. Feel free to contribute.  I have files with variable definitions. Variables consist of uppercase letters or underscore _ and their values follow after the :=. The values can contain other variables. This is Gnom.def:  NAME:=Gnom FULL_NAME:=$FIRST_NAME $NAME FIRST_NAME:=Sman STREET:=Mainstreet 42 TOWN:=Nowhere BIRTHDAY:=May 1st, 1999   Then there is another file form.txt with a template form:  $NAME Full name: $FULL_NAME Address: $STREET in $TOWN Birthday: $BIRTHDAY Don't be confused by $NAMES   Now I want a script which replaces the variables (marked with $ and the identifier) in the form by the definitions in the other file, recursively, if necessary, so I get this text back:  Gnom Full name: Sman Gnom Address: Mainstreet 42 in Nowhere Birthday: May 1st, 1999 Don't be confused by $NAMES   The last line is to ensure that no substrings of variables get replaced accidentally.
102311
I'm trying to create a new variable using the value of an existing variable as part of the variable name.  filemsg"$word1"=" "   I've also tried   filemsg$word1=" "  filemsg${word1}=" "   on all attempts I get the following when that line executes,  cicserrors.sh[45]: filemsgCICS= : not found [No such file or directory]
89893
The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?  The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.
44059
I have one input file and run some command but want the output to be saved with the same name as the input file has.  I tried below command but it makes the output file blank:  cat file1 | grep "YISHA" &gt; file1
106453
I am supposed to use ls to find files that end in a certain letter, but it does not matter if the file has an extension or not.  For example, I want it to do this  &gt; ls test test.txt test.ascii other.txt  &gt; ls [something] test test.txt test.ascii  So that I can find files that end with a 't', but it doesn't include the file where the extension ends in t  Edit: I am supposed to assume that the only period characters in the filename will be for the extension and there will be no others
85051
I have a text file named "Hex_data.txt". I want to load content of Hex_data.txt into a variable name RAM in verilog. When I try this, I get an error that the text file can't be found. Where is this file loaded from?  The content of "hex_data.txt" :            21            a4          2a          26          7a          ff           6f   I want to create a variable name "RAM" defined like:   reg [6:0] RAM; in which the above content save like:  RAM[0]=21     RAM[1]=a4           RAM[2]=2a             RAM[3]=26            RAM[4]=7a             RAM[5]=ff             RAM[6]=6f   I wrote a code:  module file_read;      reg [7:0] RAM [0:6];          initial $readmemh("Hex_data.txt", RAM);   integer i;               initial begin                    $display("data:");                for (i=0; i &lt; 7; i=i+1)                $display("%d:%h",i,RAM[i]);              end                 endmodule        But the above code not working. How can i get desired output?
26387
I have a text file in the root of my web app  and I'd like to load it into a variable in javascript.. in groovy I would do this:  def fileContents = 'http://localhost/foo.txt'.toURL().text; println fileContents;   How can I get a similar result in javascript?
21860
I'm trying to debug a Python script by placing a print("foo=" + foo) statement in my code.  But where does the output appear?     It doesn't appear on the Python Console, and it doesn't appear on the area that appears when you drag the lower edge of the infobar downwards (what is the name for this area? My script errors show up in red here.)
65920
I have a input file FILE1.TXT as below.     11 id1   12   13 AGE = 20   14 NAME = NAME1   15   16 id2   17   18 AGE = 30   19 NAME = NAME2   .   .   .   110 idXYZ   111   112 AGE = AGEXYZ   113 NAME = NAMEXYZ   114   115 idZZZ   116     I want to search all the fields that belong to a particular Id and get the value for NAME  I managed to loop through each Id and formed the below command for each Id as required.  sed -n '/11/,/14/p' FILE1.TXT | grep NAME | awk -F "= " '{print $2}'  The problem here is, I get the output NAME1, in addition to that, I also get NAMEXYZ.  What should be changed so that I only get NAME1 but not NAMEXYZ?  As a workaround, the below commands work.  sed -n '/11/,/14/p' FILE1.TXT | grep NAME | awk -F "= " '{print $2}'|head -1  Is there any 'switch' or am I missing something?
108395
All I wrote in the interpreter was as follows:  &gt;&gt;&gt; print "Hello, World!"   File "&lt;stdin&gt;", line 1     print "Hello, World!"                         ^ SyntaxError: invalid syntax   How did I even get an error? All I tried to do was run a print command.