I am testing below python code to export content from one txt file to another but in destination contents are getting copied with some different language (may be chinese) with improper
# - *- coding: utf- 8 - *-
from sys import argv
from os.path import exists
script,from_file,to_file = argv
print "Does the output file exist ? %r" %exists(to_file)
print "If 'YES' hit Enter to proceed or terminate by CTRL+C "
raw_input('?')
infile=open(from_file)
file1=infile.read()
outfile=open(to_file,'w')
file2=outfile.write(file1)
infile.close()
outfile.close()
try this code to copy 1 file to another :
with open("from_file") as f:
with open("to_file", "w") as f1:
for line in f:
f1.write(line)
Related
My problem is after executing below code I am able to see outputs of each command in shell. How can I get that shell output to the file
I have tried with the below but it does not work
python pr.py >> pr.txt
import os
f=open("pr1.txt","r")
df=0
for i in f:
df=df+1
if df==4:
break
print i
os.system("udstask expireimage -image" + i)
After executing "os.system("udstask expireimage -image" + i)" every time this will display status of the command to the file
You could try something like :
import os
f=open("pr1.txt","r")
df=0
for i in f:
df=df+1
if df==4:
break
print i
os.system("udstask expireimage -image" + i + " > pr.txt")
It would redirect the output of the command to pr.txt.
You should use subprocess instead of os.system which has more efficient stream handling and gives you more control while calling a shell command:
import os
import subprocess
f=open("pr1.txt","r")
df=0
for i in f:
df=df+1
if df==4:
break
print i
task = subprocess.Popen(["udstask expireimage -image" + i],stdout=subprocess.PIPE,shell=True)
task_op = task.communicate()
task.wait()
Now you have your output stored in task_op which you can write onto a file or do whatever you wish to. It is in tuple form and you may need to write only required part.
i am trying to copy a file from a local drive to a Network storage. The file is a TXT file with 6380 lines. Opening the Target file, the copy of the file is not complete, it stops at line 6285 in the middle of the line. The File Itself is a G-Code with 103 kb.
Source File Line 6285: "Z17.168 Y7.393" and the file continues...
Target File Line 6285: "Z17.168 Y7.3" after this its the end of the file.
I tired several differnt copy operations:
from shutil import copyfile
copyfile(WorkDir + FileName, CNCDir + FileName)
or
os.system("copy "+WorkDir + FileName +" " + CNCDir + FileName)
or also the DOS XCOPY command.
The weird thing is, that if i perform the copy command in a separate dos window with the same syntax it works perfect, just by executing it from the PYTHON script, it does not copy the complete file.
Any ideas?
Get a few "debugging" conformation using the following:
Option 1 (blunt reading, should print content to cmd console or editor stdout):
file = open(“testfile.text”, “r”)
print file.read()
Option 2 (reading + loading filecontent into memory, write content from memory to new file):
file = open(“testfile.text”, “r”)
count_lines = 0
counted_lines = 6380
content = []
for line in file:
count_line += 1
content.append(line)
print 'row : "%s" content : "%s"' % (count_lines, file)
if counted_lines == count_lines:
dest_file = open(“new_testfile.txt”,”w”)
for item in content:
dest_file.write(item)
dest_file.close()
else:
print 'error at line : %s' % count_lines
Option 3 (excludet character issue at line 6285 and show its a memory loading issue):
from itertools import islice
# Print the "6285th" line.
with open(“testfile.text”) as lines:
for line in islice(lines, 6284, 6285):
print line
Option 4 is found here.
and
Option 5 is:
import linecache
linecache.getline(“testfile.text”, 2685)
Using Option 1 on the target file gives me:
Z17.154 Y7.462
Z17.159 Y7.439
Z17.163 Y7.416
Z17.168 Y7.3
"done"
Press any key to continue . . .
Using Option 2 gives:
row : "6284" content : "<open file 'Z:\\10-Trash\\APR_Custom.SPF', mode 'r' at 0x0000000004800AE0>"
row : "6285" content : "<open file 'Z:\\10-Trash\\APR_Custom.SPF', mode 'r' at 0x0000000004800AE0>"
And a TXT File with the same content like the Target file:
Last 3 lines:
Z17.159 Y7.439
Z17.163 Y7.416
Z17.168 Y7.3
I tried option 4 -6 aswell but i dont see a purpose behind that. With Option 5 I had to change the line numbe to 6284 because list was out of range with that number.
from itertools import islice
# Print the "6285th" line.
with open(CNCDir + FileName) as lines:
for line in islice(lines, 6284, 6285):
print "Option 3:"
print line
f=open(CNCDir + FileName)
lines=f.readlines()
print "Option 4:"
print lines[6284]
import linecache
print "Option 5:"
print linecache.getline(CNCDir + FileName, 6285)
Out file from Command line:
Copy to CNC:
Source: C:\F-Engrave\WorkDir\APR_Custom.SPF
Traget: Z:\10-Trash\APR_Custom.SPF
Option 3:
Z17.168 Y7.3
Option 4:
Z17.168 Y7.3
Option 5:
Z17.168 Y7.3
"done"
Press any key to contiune. . .
I've written one small python script to fix the checksum of L3-4 protocols using scapy. When I'm running the script it is not taking command line argument or may be some other reason it is not generating the fix checksum pcap. I've verified the rdpcap() from scapy command line it is working file using script it is not getting executed. My program is
import sys
import logging
logging.getLogger("scapy").setLevel(1)
try:
from scapy.all import *
except ImportError:
import scapy
if len(sys.argv) != 3:
print "Usage:./ChecksumFixer <input_pcap_file> <output_pcap_file>"
print "Example: ./ChecksumFixer input.pcap output.pcap"
sys.exit(1)
#------------------------Command Line Argument---------------------------------------
input_file = sys.argv[1]
output_file = sys.argv[2]
#------------------------Get The layer and Fix Checksum-------------------------------
def getLayer(p):
for paktype in (scapy.IP, scapy.TCP, scapy.UDP, scapy.ICMP):
try:
p.getlayer(paktype).chksum = None
except: AttributeError
pass
return p
#-----------------------FixPcap in input file and write to output fi`enter code here`le----------------
def fixpcap():
paks = scapy.rdpcap(input_file)
fc = map(getLayer, paks)
scapy.wrpcap(output_file, fc)
The reason your function is not executed is that you're not invoking it. Adding a call to fixpcap() at the end of your script shall fix this issue.
Furthermore, here are a few more corrections & suggestions:
The statement following except Exception: should be indented as well, as follows:
try:
from scapy.all import *
except ImportError:
import scapy
Use argparse to parse command-line arguments.
Wrap your main code in a if __name__ == '__main__': block.
I'm using Python 2.7.2 and PyScriptor to create a script that I hope to use to first find a file of type (.shp) and then check to see if there is a matching file with the same name but with a (.prj) suffix. I'm stuck in the first part. I hope to share this script with others so I am trying to make the starting folder/directory a variable. Here's my script so far:
# Import the operating and system modules.
import os, sys
def Main():
# Retrieve the starting folder location.
InFolder = sys.argv[1]
#InFolder = "C:\\_LOCALdata\\junk"
os.chdir(InFolder)
print os.path.exists(Infolder)
print InFolder
# Begin reading the files and folders within the starting directory.
for root, dirs, files in os.walk(InFolder):
print os.path.exists(root)
for file in files:
print file
if file.endswith(".py"):
print os.path.join(root, file)
elif file.endswith(".xlsx"):
print os.path.join(root, file)
elif file.endswith(".shp"):
print "Shapefile present."
elif file.endswith(".txt"):
print "Text file present."
else:
print "No Python, Excel or Text files present."
return()
print "End of Script."
sys.exit(0)
if __name__ == '__main__':
sys.argv = [sys.argv[0], r"C:\_LOCALdata\junk"]
Main()
The only result I have gotten so far is:
*** Remote Interpreter Reinitialized ***
>>>
End of Script.
Exit code: 0
>>>
Any suggestions?
Layne
You're exiting your script before it even has a chance to get started!. Remove or indent these lines:
print "End of Script."
sys.exit(0)
Starting procedurally from the top (like python does), we:
Import libraries
Define the Main funcion.
Print a line, and immediately exit!
Your __name__ == '__main__' is never reached.
Oh man - duh. Thanks for the input. I did get it to work. The code searches for shapefiles (.shp) and then looks for the matching projection file (.prj) and prints the shapefiles that do not have a projection file. Here is the finished code:
# Import the operating and system modules.
import os, sys
def Main():
# Retrieve the starting folder location.
InFolder = sys.argv[1]
text = (InFolder + "\\" + "NonProjected.txt")
outFile = open(text, "w")
# Begin reading the files and folders within the starting directory.
for root, dirs, files in os.walk(InFolder):
for file in files:
if file.endswith(".shp"):
PRN = os.path.join(root,(str.rstrip(file,"shp") + "prj"))
if os.path.exists(PRN):
pass
else:
outFile.write((str(os.path.join(root,file))) + "\n")
print os.path.join(root,file)
else:
pass
outFile.close()
print
print "End of Script."
sys.exit(0)
return()
#================================================================================
if __name__ == '__main__':
sys.argv = [sys.argv[0], r"G:\GVI2Hydro"]
#sys.argv = [sys.argv[0], r"C:\_LOCALdata"]
#sys.argv = [sys.argv[0], r"U:"]
Main()
I have a .txt file with multiple lines (Different yet simular for each one) that I want to add a "*.tmp" at the end.
I'm trying to use python2.7 regex to do this.
Here is what I have for the python script:
import sys
import os
import re
import shutil
#Sets the buildpath variable to equal replace one "\" with two "\\" for python code to input/output correctly
buildpath = sys.argv[1]
buildpath = buildpath.replace('\\', '\\\\')
#Opens a tmp file with read/write/append permissions
tf = open('tmp', 'a+')
#Opens the selenium script for scheduling job executions
with open('dumplist.txt') as f:
#Sets line as a variable for every line in the selenium script
for line in f.readlines():
#Sets build as a variable that will replace the \\build\path string in the line of the selenium script
build = re.sub (r'\\\\''.*',''+buildpath+'',line)
#Overwrites the build path string from the handler to the tmp file with all lines included from the selenium script
tf.write(build)
#Saves both "tmp" file and "selenium.html" file by closing them
tf.close()
f.close()
#Copies what was re-written in the tmp file, and writes it over the selenium script
shutil.copy('tmp', 'dumplist.txt')
#Deletes the tmp file
os.remove('tmp')
#exits the script
exit()
Current File Before Replacing the Line:
\\server\dir1\dir2\dir3
DUMP3f2b.tmp
1 File(s) 1,034,010,207 bytes
\\server\dir1_1\dir2_1\dir3_1
DUMP3354.tmp
1 File(s) 939,451,120 bytes
\\server\dir1_2\dir2_2\dir3_2
Current file after replacing string:
\*.tmp
DUMP3f2b.tmp
1 File(s) 1,034,010,207 bytes
\*.tmp
DUMP3354.tmp
1 File(s) 939,451,120 bytes
\*.tmp
Desired file after replacing string:
\\server\dir1\dir2\dir3\*.tmp
DUMP3f2b.tmp
1 File(s) 1,034,010,207 bytes
\\server\dir1_1\dir2_1\dir3_1\*.tmp
DUMP3354.tmp
1 File(s) 939,451,120 bytes
\\server\dir1_2\dir2_2\dir3_2\*.tmp
If anyone could help me in solving this that would be great. Thanks :)
You should use capturing groups:
>>> import re
>>> s = "\\server\dir1\dir2\dir3"
>>> print re.sub(r'(\\.*)', r'\\\1\*.tmp', s)
\\server\dir1\dir2\dir3\*.tmp
Then, modify build = re.sub (r'\\\\''.*',''+buildpath+'',line) line this way:
build = re.sub (r'(\\.*)', r'\\\1%s' % buildpath, line)
Also, you shouldn't call readlines(), just iterate over f:
for line in f: