Error when opening txt file in Python - python

I have to work with a txt file and to do that I used the following code:
inputFile = open("C:/Abaqus_JOBS/Job-M1-3_4.inp", "r") #CAE INPUT FILE
However I get this error when I ran this line in a specific application for running python scripts available in another program. I don't get any error when I ran it in Spyder.
TypeError: an integer is required
I don't have a clue why this error occurs....
EDIT:
lines of code until line in question
import os
from os import *
from abaqus import *
from odbAccess import *
from abaqusConstants import *
import time
import itertools
os.chdir('C:\\Abaqus_JOBS')
LCKf = 'C:\\Abaqus_JOBS\\Job-M1-3_2.lck'
STAf = 'C:\\Abaqus_JOBS\\Job-M1-3_2.sta'
def get_num_part(s):
for i in xrange(len(s)):
if s[i:].isdigit():
return s[i:]
return ''
if not path.exists(LCKf):
time.sleep(1)
while path.exists(LCKf) and path.isfile(LCKf) and access(LCKf, R_OK):
variableX = 0
else:
odb = openOdb(path='Job-M1-3_2.odb')
#get CF
#session.odbs[name].steps[name].frames[i].FieldOutput
myAssembly = odb.rootAssembly
myAssemblyName = odb.rootAssembly.name
nsteps=len(odb.steps.values())
step1 = odb.steps.values()[nsteps-1]
step1Name = odb.steps.values()[nsteps-1].name
myInstanceName = odb.rootAssembly.instances.values()[0].name
dCF3=[]
dCF3v=[]
coordFv=[]
fileData = [] #array with the input file
nodes = [] #array with the content of *NODES
inputFile = open("C:/Abaqus_JOBS/Job-M1-3_4.inp", "r") #CAE INPUT FILE
#fileData = variable with all the lines of the inp file
for line in inputFile:
fileData.append([x.strip() for x in line.split(',')])
the error is:
Traceback (most recent call last):
File "c:/Abaqus_JOBS/results.py", line 47, in <module>
inputFile = open("C:/Abaqus_JOBS/Job-M1-3_4.inp", "r") #CAE INPUT FILE
TypeError: an integer is required

With the
from os import *
You're importing all os stuff in the global namespace, including os.open(). Don't do this.
The second argument, flags, is defined as integer constants while you're providing a single-character string r. This is basically what DSM was telling you and what Lattyware said.
open() included in Python by default in the global namespace, which you were expecting apparently, is different:
Note: This function is intended for low-level I/O. For normal usage,
use the built-in function open(), which returns a “file object” with
read() and write() methods (and many more). To wrap a file descriptor
in a “file object”, use fdopen().

Related

How do I write the time from datetime to a file in Python?

I'm trying to have my Python code write everything it does to a log, with a timestamp. But it doesn't seem to work.
this is my current code:
filePath= Path('.')
time=datetime.datetime.now()
bot_log = ["","Set up the file path thingy"]
with open ('bot.log', 'a') as f:
f.write('\n'.join(bot_log)%
datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))
print(bot_log[0])
but when I run it it says:
Traceback (most recent call last):
File "c:\Users\Name\Yuna-Discord-Bot\Yuna Discord Bot.py", line 15, in <module>
f.write('\n'.join(bot_log)%
TypeError: not all arguments converted during string formatting
I have tried multiple things to fix it, and this is the latest one. is there something I'm doing wrong or missing? I also want the time to be in front of the log message, but I don't think it would do that (if it worked).
You need to put "%s" somewhere in the input string before string formatting. Here's more detailed explanation.
Try this:
filePath= Path('.')
time=datetime.datetime.now()
bot_log = "%s Set up the file path thingy\n"
with open ('bot.log', 'a') as f:
f.write(bot_log % datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))
print(bot_log)
It looks like you want to write three strings to your file as separate lines. I've rearranged your code to create a single list to pass to writelines, which expects an iterable:
filePath= Path('.')
time=datetime.datetime.now()
bot_log = ["","Set up the file path thingy"]
with open ('bot.log', 'a') as f:
bot_log.append(datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))
f.writelines('\n'.join(bot_log))
print(bot_log[0])
EDIT: From the comments the desire is to prepend the timestamp to the message and keep it on the same line. I've used f-strings as I prefer the clarity they provide:
import datetime
from pathlib import Path
filePath = Path('.')
with open('bot.log', 'a') as f:
time = datetime.datetime.now()
msg = "Set up the file path thingy"
f.write(f"""{time.strftime("%d-%b-%Y (%H:%M:%S.%f)")} {msg}\n""")
You could also look at the logging module which does a lot of this for you.

Python script that executes another python script

I'm pretty new to the world of python. I decided to do a project but came to a stop, after my script wouldn't execute the right way. In which I mean the script that I need to be executed on its own through another script keeps on giving me nothing or some syntax error instead of all the stuff that is supposed to be happening (converting files). The other script in question writes new lines into the other script to change the file name (to be converted) to the newest file. The file looks something like this:
import glob
import os.path
folder_path = r'C:\User\Desktop\Folder\Audio'
file_type = r'\*mp4'
files = glob.glob(folder_path + file_type)
max_file = max(files, key=os.path.getctime)
mp3_file = max_file.replace('.mp4', '')
with open ("file.py", 'w') as f:
f.write("")
with open ("file.py", 'w') as f:
f.write('from moviepy.editor import *\n' "mp4_file = '{}'\n"
"mp3_file = '{}.mp3'\n" 'videoclip = VideoFileClip(mp4_file)\n' 'audioclip = videoclip.audio\n'
'audioclip.write_audiofile(mp3_file)\n' 'audioclip.close()\n' 'videoclip.close()\n'.format(max_file, mp3_file))
exec(open("file.py").read())
Right now it gives this error:
Traceback (most recent call last):
File "C:\Users\Desktop\Folder\Audio\File Manager.py", line 19, in <module>
exec(open("file.py").read())
File "<string>", line 2
mp4_file = 'C:\User\Desktop\Folder\Audio\test.mp4'
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
I plan not on using that exact line of code to execute my python file since there are many alternatives, but if I was on the right trail, then I might as well. The other file that's supposed to be executed has generic file converting code:
from moviepy.editor import *
mp4_file = 'C:\User\Desktop\Folder\Audio\test.mp4'
mp3_file = 'C:\User\Desktop\Folder\Audio\test.mp3'
videoclip = VideoFileClip(mp4_file)
audioclip = videoclip.audio
audioclip.write_audiofile(mp3_file)
audioclip.close()
videoclip.close()
Other solutions mostly gave me a blank inactive shell; if the answer to this problem that it's impossible, then it might as well be, and I'll take that as a valid answer, but please explain why.
Corrections
You are using different quotes while writing to the file, from single quotes ' to double ", update it to be more consistent.
The error is suggesting that while writing to the file it is also writing some unicode characters which it cannot read hence the unicode error (look at where the carrot ^ is pointing at, it's a blank space since it's not a printable character).
Suggestions
Don't just write to a file and then immediately read from it. Different operating systems have different behaviour for such repeated access which will give you strange issues (this is not your issue tho)
Just create a function extractMp3FromVideoFile which takes two arguements max_file and mp3_file
Instead of writing to a file and increasing the HDD IO simply put the file's code into a variable and then exec it.
Solution
import glob
import os.path
folder_path = r'C:\User\Desktop\Folder\Audio'
file_type = r'\*mp4'
files = glob.glob(folder_path + file_type)
max_file = max(files, key=os.path.getctime)
mp3_file = max_file.replace('.mp4', '')
code = "from moviepy.editor import *\nmp4_file = '{}'\nmp3_file = '{}.mp3'\nvideoclip = VideoFileClip(mp4_file)\naudioclip = videoclip.audio\naudioclip.write_audiofile(mp3_file)\naudioclip.close()\nvideoclip.close()\n".format(max_file, mp3_file)
exec(code)

Define type for fileinput.input file object

I am trying to find & replace in file using below code snippet:
from pathlib import Path
import fileinput
import re
TEXT_FILE_PATH = Path.cwd() / "temp.txt"
FIND_PUBLIC_PATH_REGEX = r"(publicPath: ').*(',)"
REPLACE_PUBLIC_PATH_REGEX = r"\1/\2"
with fileinput.input(TEXT_FILE_PATH, inplace=True) as file:
for line in file:
print(re.sub(FIND_PUBLIC_PATH_REGEX, REPLACE_PUBLIC_PATH_REGEX, line), end="")
The problem is I am getting type error on last line which says:
No overloads for "sub" match the provided arguments
Argument types: (Literal['(publicPath: \').*(\',)'], Literal['\\1/\\2'], AnyStr#input)Pylance(reportGeneralTypeIssues)
I can't understand why I am getting this error.
Regards.

How can I make python script(X) reload dynamically changing variables in another module(Y) and then re-import updated module(Y) in same script(X)?

I'm new to Python, I'm stuck with a code. I have tried my best to show my problem with below sample code. I'm playing with 4 files.
This is the runme file. That I'm running.
command > python runme.py
import os
with open("schooldata.txt", "r") as filestream: #opening schooldata.txt file
for line in filestream:
currentline = line.split(",")
a = currentline[0]
b = currentline[1]
c = currentline[2]
#creating a school_info.py file with value of a,b,c that are further imported by mainfile.py
f = open('school_info.py','w')
f.write("a= \"" + currentline[1] + "\"\n")
f.write("b= \"" + currentline[2] + "\"\n")
f.write("c= \"" + currentline[3] + "\"\n")
f.close()
#importing mainfile.py and calling its functions.
from mainfile import give_to_student
give_to_student("Rickon")
from mainfile import give_to_teacher
give_to_student("Carolina")
Second file is schooldata.txt from where I want to read the value of a,b,c. This is our main school data file from which we take authorization data. I'm reading line by line from this file and creating a,b,c by splitting it with (,).
12313,mshd1732,2718230efd,
fhwfw,382842324,238423049234230,
fesj32,282342rnfewk,43094309432,
fskkfns,48r209420fjwkfwk,2932042fsdfs,
38234290,fsfjskfjsdf,2942094929423,
Third file is school_info.py which I'm creating with this data everytime. This file is created everytime when a line is read from schooldata.txt file. So fresh file everytime with fresh and unique data of a,b,c.
a = "asb12"
b = "121002"
c = "mya122344"
Now here comes the mainfile.py which is having functions like give_to_student and give_to_teacher. This file is importing data from school_info.py, so as to create authorization code using values of a,b,c.
and function definition of give_to_student and give_to_teacher which uses these function definitions.
import os
import schoollib #(internal school lib)
#importing School_info.py file so as to get value of a,b,c
from school_info import *
#It creates authorisation code internally
lock = auth(a,b,c,d)
#This authorisation code is used to call internal function
def give_to_student():
lock.give(student)
def give_to_teacher():
lock.give(teacher)
So now let me share the exact problem that I'm facing as of now, I'm unable to get authorization code loaded for mainfile.py everytime it is imported in runme.py file. When I'm calling runme.py file it is giving same authorization code to all users every time.
It is not able to use authorization code that is create after reading second line of schooldata.txt
With mainfile.py file If I'm trying to reload module using. import importlib and then importlib.reload(mainfile.py) in runme.py.
#Added it in runme.py file
import importlib
importlib.reload(mainfile)
It is still giving authorization for first line of data(schooldata.txt).
Similar thing I tried in mainfile.py.
I tried to import importlib and then importlib.reload(school_info).
#added it in mainfile.py
import importlib
importlib.reload(school_info)
importlib.reload(school_info)
NameError: name 'school_info' is not defined
But it giving error, that school_info module doesn't exist.
Please throw some light on it, and how can I make it work.
P.S. I'm using python 3.5. Thanks
Why don't you try to combine the school_info.py and mainfile.py.
If you can run a combined loop.
import os
import schoollib #(internal school lib)
with open("schooldata.txt", "r") as filestream: #opening schooldata.txt file
for line in filestream:
currentline = line.split(",")
a = currentline[0]
b = currentline[1]
c = currentline[2]
#It creates authorisation code internally
lock = auth(a,b,c,d)
#This authorisation code is used to call internal function
def give_to_student():
lock.give(student)
def give_to_teacher():
lock.give(teacher)
#function calling
give_to_student("Rickon")
give_to_student("Carolina")
I hope this solves your purpose.

Python - error while pickling [duplicate]

I'm using python3.3 and I'm having a cryptic error when trying to pickle a simple dictionary.
Here is the code:
import os
import pickle
from pickle import *
os.chdir('c:/Python26/progfiles/')
def storvars(vdict):
f = open('varstor.txt','w')
pickle.dump(vdict,f,)
f.close()
return
mydict = {'name':'john','gender':'male','age':'45'}
storvars(mydict)
and I get:
Traceback (most recent call last):
File "C:/Python26/test18.py", line 31, in <module>
storvars(mydict)
File "C:/Python26/test18.py", line 14, in storvars
pickle.dump(vdict,f,)
TypeError: must be str, not bytes
The output file needs to be opened in binary mode:
f = open('varstor.txt','w')
needs to be:
f = open('varstor.txt','wb')
Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.
import pickle
class MyUser(object):
def __init__(self,name):
self.name = name
user = MyUser('Peter')
print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'
with open(filename,'wb') as file_object:
file_object.write(serialized)
with open(filename,'rb') as file_object:
raw_data = file_object.read()
deserialized = pickle.loads(raw_data)
print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
pickle uses a binary protocol, hence only accepts binary files. As the document said in the first sentence, "The pickle module implements binary protocols for serializing and de-serializing".

Categories

Resources