I am new to python and I have a question about a piece of python code that creates a cleaned up output file from a model output file. This code was written for a Mac user, but now I want to run it in Windows. But it gives an error message. Could you help me in converting this code so I can use it in Windows? Thanks.
import sys
if len(sys.argv) > 1:
fileName = sys.argv[1]
else:
print "selected_um_b.out" #insert file name here
sys.exit()
f = open(fileName)
counter = 0
fw = open(fileName+".cleaned", 'w')
for line in f:
line = line.strip()
counter = counter + 1
if counter <= 4:
fw.write(line+"\n");
continue
values = line.split("\t")
if (values[4].strip() == "-99" or values[5].strip() == "0"): continue
fw.write("\t".join(values)+"\n")
f.close()
Update
The error message is:
Traceback (most recent call last): File
"C:\trial_batch\clean_output.py", line 7, in sys.exit()
SystemExit
The program expects a filename on the command line when you execute it. It appears you did not provide one, so the program exited (the sys.exit() call terminates the program).
How are you trying to use it? If you just want to convert one file, put the file and the Python script into the same directory. Replace lines 3 through 7 with filename = "yourfilename.typ" (do not indent the line); it will read the file ("yourfilename.typ" in my example) and write an output file with 'cleaned' in the filename.
Related
I've started Python recently, and I want to create a program which read a calculation in a file, execute it (using the eval() function) and write the result in another file. This program must be started with the console.
I've created the program, which works perfectly when I start it by double clicking it. But when I start the program with the console, it doesn't write the result in the file, and I don't get any errors. I know the calculation has been done, because the result is written in the console.
I've tried by running the program with .py extension, and compiling it to an executable, using pyinstaller. They work with a double-click, but not from the console.
Here are the commands I used to run the programs :
F:\Path\To\App\calculator.exe
C:\Path\To\Python\python.exe F:\Path\To\App\calculator.py
The code I use to read, evaluate and write the calculation
input = open('calcul.txt', 'r')
output = open('result.txt', 'w')
calcul = input.read()
print(calcul)
print(eval(calcul).toString())
output.write(eval(calcul).toFileString())
input.close()
output.close()
def toString(self):
number = str (round(self.m_number, 4))
number_scientific = str(format(self.m_number, ".3E"))
imprecision = str (round(self.m_imprecision, 4))
imprecision_scientific = str(format(self.m_imprecision, ".3E"))
relative_imprecision = str(round(self.m_relative_imprecision * 100, 2))
return "\t Number \t\t= " + number + " \t= " + number_scientific + "\n\t Imprecision \t\t= " + imprecision + " \t= " + imprecision_scientific + "\n\t Relative Imprecision \t= " + relative_imprecision + "%\n\t"
def toFileString(self):
return str (round(self.m_number, 4)) + '\n' + str (round(self.m_imprecision, 4))
When I run the console as administrator, I have that:
C:\WINDOWS\system32>F:\Users\Ludovic\Desktop\Apprentissage\C++\Qt\calculator\python_calculator\calculator.exe
Traceback (most recent call last):
File "calculator.py", line 376, in <module>
calcul = input.read()
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\WINDOWS\\system32\\calcul.txt'
[26580] Failed to execute script calculator
C:\WINDOWS\system32>C:\Users\Ludovic\AppData\Local\Programs\Python\Python38\python.exe F:\Users\Ludovic\Desktop\Apprentissage\C++\Qt\calculator\python_calculator\calculator.py
Traceback (most recent call last):
File "F:\Users\Ludovic\Desktop\Apprentissage\C++\Qt\calculator\python_calculator\calculator.py", line 373, in <module>
input = open('calcul.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'calcul.txt'
Run console as administrator
Add path tou your input and output files
input = open('your_path_to_file\\calcul.txt', 'r')
output = open('your_path_to_file\\result.txt', 'w')
Or put files in script folder and then call them like this
import sys
input = open(sys.path[0]+'\\calcul.txt', 'r')
output = open(sys.path[0]+'\\result.txt', 'w')
Update
for unversal file path for .exe and .py try this (files should be in .exe and .py folder)
import sys
if getattr(sys, 'frozen', False):
application_path = ''
else:
application_path = sys.argv[0]+'\\'
input = open(application_path+'calcul.txt', 'r')
output = open(application_path+'result.txt', 'w')
Maybe you are not in the directory you wished write your txt file for exemple:
if you are here in the cmd: MyFolder\
and you execute your python file by writting: python MyFolder\Python_prog\program.py
the .txt file will be written in MyFolder\ not in MyFolder\Python_prog\
I'm not sure because I've never tried out with python but I had the same kind of Errors with JavaScript
I'm trying to run the following python code for to exercise
#!/bin/python3
import os
import sys
#
# Complete the maximumDraws function below.
#
def maximumDraws(n):
return n+1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = maximumDraws(n)
fptr.write(str(result) + '\n')
fptr.close()
but i get this error message
Traceback (most recent call last):
File "maximumdraws.py", line 13, in <module>
fptr = open(os.environ['OUTPUT_PATH'], 'w')
File "/home/inindekikral/anaconda3/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'OUTPUT_PATH'
My Operation System is Linux Mint 19 Cinnamon.
What i have to do?
I'm sure there are other ways to do this, but for Hackerrank exercises, the file pointer was opened this way:
fptr = open(os.environ['OUTPUT_PATH'], 'w')
... and I want it to just go to standard output.
I just changed that line to
fptr = sys.stdout # stdout is already an open stream
and it does what I want.
Note that on the one hand, os.environ['OUTPUT_PATH'] is a string, while fptr is a stream/file pointer.
Variations:
If you want to write to a file, you can do it the way suggested above (setting the OUTPUT_PATH environment variable).
Or, you can set the os.environ directly in python, e.g.
os.environ['OUTPUT_PATH'] = 'junk.txt' # before you open the fptr!
os.environ lets you access environment variables from your python script, it seems you do not have an environment variable with name OUTPUT_PATH. From the terminal you run your python script, before running your python code set an environment variable with name OUTPUT_PATH such as:
export OUTPUT_PATH="home/inindekikral/Desktop/output.txt"
Your python script will create a file at that location.
A KeyError means that an element doesn’t have a key. So that means that os.environ doesn’t have the key 'OUTPUT_PATH'.
Simply, change the path of the python code to your local path.
fptr = open("./result.output", 'w')
Hackerrank sends output to a file, but for practice locally, the output can be printed.
You can remove the use of ftpr by commenting out these lines
fptr = open(os.environ['OUTPUT_PATH'], 'w') and
fptr.close()
And replace line fptr.write(str(result) + '\n') with print(str(result) + '\n')
change your code like this:
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
n = int(input())
result = maximumDraws(n)
print(str(result) + '\n')
After looking for a large amount of time, I still can't seem to find an answer to my problem (I am new to python).
Here is what I'm trying to do :
Prompt the user to insert an nlps version and ncs version (both are just server builds)
Get all the filenames ending in .properties in a specified folder
Read those files to find the old nlps and ncs version
Replace, in the same .properties files, the old nlps and ncs versions by the ones given by the user
Here is my code so far :
import glob, os
import fileinput
nlpsversion = str(input("NLPS Version : "))
ncsversion = str(input("NCS Version : "))
directory = "C:/Users/x/Documents/Python_Test"
def getfilenames():
filenames = []
os.chdir(directory)
for file in glob.glob("*.properties"):
filenames.append(file)
return filenames
properties_files = getfilenames()
def replaceversions():
nlpskeyword = "NlpsVersion"
ncskeyword = "NcsVersion"
for i in properties_files:
searchfile = open(i, "r")
for line in searchfile:
if line.startswith(nlpskeyword):
old_nlpsversion = str(line.split("=")[1])
if line.startswith(ncskeyword):
old_ncsversion = str(line.split("=")[1])
for line in fileinput.FileInput(i,inplace=1):
print(line.replace(old_nlpsversion, nlpsVersion))
replaceversions()
In the .properties files, the versions would be written like :
NlpsVersion=6.3.107.3
NcsVersion=6.4.000.29
I am able to get old_nlpsversion and old_ncsversion to be 6.3.107.3 and 6.4.000.29. The problem occurs when I try to replace the old versions with the ones the user inputed. I get the following error :
C:\Users\X\Documents\Python_Test>python replace.py
NLPS Version : 15
NCS Version : 16
Traceback (most recent call last):
File "replace.py", line 43, in <module>
replaceversions()
File "replace.py", line 35, in replaceversions
for line in fileinput.FileInput(i,inplace=1):
File "C:\Users\X\AppData\Local\Programs\Python\Python36-
32\lib\fileinput.py", line 250, in __next__
line = self._readline()
File "C:\Users\X\AppData\Local\Programs\Python\Python36-
32\lib\fileinput.py", line 337, in _readline
os.rename(self._filename, self._backupfilename)
PermissionError: [WinError 32] The process cannot access the file because it
is being used by another process: 'test.properties' -> 'test.properties.bak'
It may be that my own process is the one using the file, but I can't figure out how to replace, in the same file, the versions without error. I've tried figuring it out myself, there are a lot of threads/resources out there on replacing strings in files, and i tried all of them but none of them really worked for me (as I said, I'm new to Python so excuse my lack of knowledge).
Any suggestions/help is very welcome,
You are not releasing the file. You open it readonly and then attempt to write to it while it is still open. A better construct is to use the with statement. And you are playing fast and loose with your variable scope. Also watch your case with variable names. Fileinput maybe a bit of overkill for what you are trying to do.
import glob, os
import fileinput
def getfilenames(directory):
filenames = []
os.chdir(directory)
for file in glob.glob("*.properties"):
filenames.append(file)
return filenames
def replaceversions(properties_files,nlpsversion,ncsversion):
nlpskeyword = "NlpsVersion"
ncskeyword = "NcsVersion"
for i in properties_files:
with open(i, "r") as searchfile:
lines = []
for line in searchfile: #read everyline
if line.startswith(nlpskeyword): #update the nlpsversion
old_nlpsversion = str(line.split("=")[1].strip())
line = line.replace(old_nlpsversion, nlpsversion)
if line.startswith(ncskeyword): #update the ncsversion
old_ncsversion = str(line.split("=")[1].strip())
line = line.replace(old_ncsversion, ncsversion)
lines.append(line) #store changed and unchanged lines
#At the end of the with loop, python closes the file
#Now write the modified information back to the file.
with open(i, "w") as outfile: #file opened for writing
for line in lines:
outfile.write(line+"\n")
#At the end of the with loop, python closes the file
if __name__ == '__main__':
nlpsversion = str(input("NLPS Version : "))
ncsversion = str(input("NCS Version : "))
directory = "C:/Users/x/Documents/Python_Test"
properties_files = getfilenames(directory)
replaceversions(properties_files,nlpsversion,ncsversion)
What I Want
I have written a code that opens a file (currentcode) gets it's text finds it in another file (text.txt) and replaces currentcode with a new int.
My Code
import os
currentcode = open('currentcode.txt','r+')
code = currentcode.read()
print('Choose File: ')
print('1: File One > ')
file = input('Enter Number Of File: ')
file = 'C:/text.txt'
old_text = code
new_text = str(int(code) + 1)
print('Opened File')
f1 = open(file, 'r')
f2 = open(file, 'w')
f2.write(replace(old_text, new_text))
currentcode.write(new_text)
f1.close()
f2.close()
Output After Running
When I Run This Code I Get:
Choose File:
1: File One >
Enter Number Of File: 1
Opened File
Traceback (most recent call last):
File "C:\Users\DanielandZoe\Desktop\scripys\Replace.py", line 18, in <module>
f2.write(replace(old_text, new_text))
NameError: name 'replace' is not defined
NameError: name 'replace' is not defined
That means python couldn't find a module, class or function called 'replace'.
If you want to replace text on a file, you need to get its contents as a string, not as a file-like object (like you're doing now), then you replace the contents using the replace method on your string and finally, write the contents to the desired file.
string.replace() is a method for strings:
https://docs.python.org/2/library/string.html#string.replace
what is in f2? Not a string. You should read the lines of the file.
I'm new to programming and I am trying to teach myself Python through http://learnpythonthehardway.org/.
In exercise 20, we are told to make a script like this:
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
However, when I run it through the Terminal, it returned, "IOError: File not open for reading." I'm really confused and not sure about what it meant by "not open." Here's the full account of the traceback message:
Traceback (most recent call last):
File "ex20.py", line 18, in <module>
print_all(current_file)
File "ex20.py", line 6, in print_all
print f.read()
IOError: File not open for reading
I checked that the file exists. Can someone please help? Thanks a lot!
Update:
I solved the problem by creating a separate folder, thus isolating the new .py and .txt files to a new folder by themselves. I'm wondering if the previous .py files played a role in this? I wrote a truncating script before as well, but it wouldn't make sense because I only executed the new python file.