I created a translating script that searches for a file, for example bot.json in this folder structure from the executed file: data/lang/en/. I use the following code to do it:
with open(r'data/lang/' + functions.json_module.get_config('Config')['Language'] + r'/bot.json', 'r') as f:
return json.load(f)['Bot']['starting']
functions.json_module.get_config('Config')['Language'] will return en.
What am I doing wrong?
I tried it with '\data\lang...' too but this didn't work either. I was expecting to get the translation for starting (Starting...).
Related
I have this code which along with the rest of it runs on a single file in a folder.
I want to try and run this code on 11 files in the folder. I have to pass parameters to the whole script via an .sh script which I've written.
I've searched on here and found various solutions which have not worked.
def get_m3u_name():
m3u_name = ""
dirs = os.listdir("/tmp/")
for m3u_file in dirs:
if m3u_file.endswith(".m3u") or m3u_file.endswith(".xml"):
m3u_name = m3u_file
return m3u_name
def remove_line(filename, what):
if os.path.isfile(filename):
file_read = open(filename).readlines()
file_write = open(filename, 'w')
for line in file_read:
if what not in line:
file_write.write(line)
file_write.close()
m3ufile = get_m3u_name()
I have tried a different method of deleting the file just processed then looping the script to run again on the next file as I can do this manually but when I use
os.remove(m3ufile)
I get file not found either method of improving my code would be of great help to me. I'm just a newbie at this but pointing me in the right direction would be of great help.
I'm creating a very basic python program that allows a user to enter a command that is then ran as code.
For example I have imported a file called textScripts.py: within that file there is a function called createFile(). When the user enters textScripts.createFile() it is passed into exec(). It runs without error and exits the program but the file isn't created!
I know the createFile() function works because if I put textScripts.createFile() in the code it creates a file.
Here is the relevant snippet of code:
commandList=[]
while(commandRun):
count = 0
commandList.append(input(">>>"))
exec(commandList[count])
print(commandList[count])
count += 1
here is a screenshot of the code being run:
>>> textScripts.createFile()
>>>
here is a screenshot of the folder:
__pyCache__
textScripts.py
CLIFile.py
there should be a file in this folder
here is the function createFile():
def createFile(
destination = os.path.dirname(__file__),
text = "Sick With the Python\n"
):
''' createFile(destination, text)
This script creates a text file at the
Specified location with a name based on date
'''
date = t.localtime(t.time())
name = "%d_%d_%d.txt" %(date[1], date[2], date[0])
if not(os.path.isfile(destination + name)):
f = open(destination + name, "w")
f.write( text )
f.close
else:
print("file already exists")
I apologize in advance if this is an obvious questions; I'm new to python and have been looking for hours for an answer as to why this happens.
You save file to wrong folder (you can insert "print(destination + name)" in your function)
You need to replace this:
destination + name
to this:
os.path.join(destination, name)
PS:
You don't close the file (f.close -> f.close())
The best way to open any resource is using "with".
For example:
with open('file.txt', 'w') as f:
f.write('line')
I'm trying to put all the anchor text on a page in a txt file
print(anchor.get('href'))
with open('file.txt', 'a') as fd:
fd.write(anchor.get('href') + '\n')
and the script executes with no errors but I cannot find file.txt anywhere on my computer. Am I missing out on something really obvious?
With file open mode a (append) the file will be created if it doesn't already exist, otherwise writes will be appended to the end of the file. As written in the question, the file will be created in the current directory of the running process... look there.
from bs4 import BeautifulSoup
import requests
response = requests.get('http://httpbin.org/')
soup = BeautifulSoup(response.text)
with open('file.txt', 'a') as fd:
links = (link.get('href') for link in soup.find_all('a'))
fd.write('\n'.join(links) + '\n')
Try to set a full path to filename, so you can find in this path.
Example:
print(anchor.get('href'))
with open('/home/wbk/file.txt', 'a') as fd:
fd.write(anchor.get('href') + '\n')
And yes, you can use 'a' to create a new file, although this is not a good practice. The 'a' is to append data to the end of an existing file as describes doc
The following code works for me:
with open("example.txt","a") as a:
a.write("hello")
are you sure that the file isn't in your computer? In which ways you have demonstrated it? In my case, i work with eclipse IDE, so I have to refresh the Eclipse file explorer to see it..
Try this:
with open("prova.txt","a") as a:
a.write("ciao")
try: open("prova.txt","r")
except: print "file doesn't exist"
I have a set of XML files that I need to read and format into a single CSV file. In order to read from the XML files, I have used the solution mentioned here.
My code looks like this:
from os import listdir
import xml.etree.cElementTree as et
files = listdir(".../blogs/")
for i in range(len(files)):
# fname = ".../blogs/" + files[i]
f = open(".../blogs/" + files[i], 'r')
contents = f.read()
tree=et.fromstring(contents)
for el in tree.findall('post'):
post = el.text
f.close()
This gives me the error cElementTree.ParseError: undefined entity: at the line tree=et.fromstring(contents). Oddly enough, when I run each of the commands on command line Python (without the for-loop though), it runs perfectly.
In case you want to know the XML structure, it is like this:
<Blog>
<date> some date </date>
<post> some blog post </post>
</Blog>
So what is causing this error, and how come it doesn't run from the Python file, but runs from the command line?
Update: After reading this link I checked files[0] and found that '&' symbol occurs a few times. I think that might be causing the problem. I used a random file to read when I ran the same commands on command line.
As I mentioned in the update, there were some symbols that I suspected might be causing a problem.
The reason the error didn't come up when I ran the same lines on the command line is because I would randomly pick a file that didn't have any such characters.
Since I mainly required the content between the <post> and </post> tags, I created my own parser (as was suggested in the link mentioned in the update).
from os import listdir
files = listdir(".../blogs/")
for i in range(len(files)):
f = open(".../blogs/" + files[i], 'r')
contents = f.read()
seek1 = contents.find('<post>')
seek2 = contents.find('</post>', seek1+1)
while(seek1!=-1):
post = contents[seek1+5:seek2+6]
seek1 = contents.find('<post>', seek1+1)
seek2 = contents.find('</post>', seek1+1)
f.close()
I'm new to python and the following piece of code is driving me crazy. It lists the files in a directory and for each file does some stuff. I get a IOError: [Errno2] No such file or directory: my_file_that_is_actually_there!
def loadFile(aFile):
f_gz = gzip.open(aFile, 'rb')
data = f_gz.read()
#do some stuff...
f_gz.close()
return data
def main():
inputFolder = '../myFolder/'
for aFile in os.listdir(inputFolder):
data = loadFile(aFile)
#do some more stuff
The file exists and it's not corrupted. I do not understand how it's possible that python first finds the file when it checks the content of myFolder, and then it cannot find itanymore... This happens on the second iteration of my for loop only with any files.
NOTE: Why does this exception happen ONLY at the second iteration of the loop?? The first file in the folder is found and opened without any issues...
This is because open receives the local name (returned from os.listdir). It doesn't know that you mean that it should look in ../myFolder. So it receives a relative path and applies it to the current dir. To fix it, try:
data = loadFile(os.path.join(inputFolder, aFile))