2

I'm trying to cut the first n lines of a file off a file, I calculate n and assign that value to myvariable

command = "tail -n +"myvariable" test.txt >> testmod.txt"
call(command)

I've imported call from subprocess. But I get a syntax error at myvariable.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
oxidising
  • 171
  • 2
  • 16

1 Answers1

5

There are two things wrong here:

  1. Your string concatenation syntax is all wrong; that's not valid Python. You probably wanted to use something like:

    command = "tail -n " + str(myvariable) + " test.txt >> testmod.txt"
    

    where I assume that myvariable is an integer, not a string already.

    Using string formatting would be more readable here:

    command = "tail -n {} test.txt >> testmod.txt".format(myvariable)
    

    where the str.format() method will replace {} with the string version of myvariable for you.

  2. You need to tell subprocess.call() to run that command through the shell, because you are using >>, a shell-only feature:

    call(command, shell=True)
    
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @Gar: you could also use a list argument: `rc = call(["tail", "-n", str(myvariable), "test.txt"], stdout=open('testmod.txt', 'a'))` – jfs Mar 23 '14 at 13:37