How to open and read from an external text file in odoo? - python-2.7

I want to open a .txt file using python in odoo and read its contents. Where should I place this .txt file for it to be opened.
What I tried,
I kept the file in the same directory as models.py and in models.py wrote the code to open the file,
try:
logFile = open('log.txt', 'r')
but this file is not opened. Please help, where should I keep log.txt for it to be located, or can I set any path for models.py to understand where log.txt is?

I just found the solution, I set the absolute path to where the .txt file is found.
import os
path = os.path.expanduser('<absolute path to .txt file>')
logFile = open(path, 'r')
this worked.

This is Python Code may be help you:
with open("log.txt") as file: # Use file to refer to the file object
data = file.read()
do something with data
print data
File handling in Python See this link : http://pymbook.readthedocs.org/en/latest/file.html

Related

Django how to open file in FileField

I need to open a file saved in a FileField, create a list with the content of the file and pass it to the template. How can I open the file? I tried with open(stocklist.csv_file.url, "wb") but it gave me a "File not found" error. If I do this:
csv_file = stocklist.csv_file.open(mode="rb")
csv_file is None. However, there is a file. If I print print("stocklist.csv_file.url: %s" % stocklist.csv_file.url) I do get
stocklist.csv_file: https://d391vo1.cloudfront.net/csv_pricechart/...ss7.csv
And if I go to the admin, I can download the file. So, how can I open a file saved in a FileField?
The .open() opens the file cursor but does not return it, since it depends of your storage (filesystem, S3, FTP...). Once opened, you can use .read() to iterate over the file content.
stocklist.csv_file.open(mode="rb")
content = stocklist.csv_file.read()
stocklist.csv_file.close()
If you want to specifically work with file descriptor then you can use your storage functionality:
from django.core.files.storage import DefaultStorage
storage = DefaultStorage()
f = storage.open(stocklist.csv_file.name, mode='rb')

Python: [Errno 2] No such file or directory

I want to open and read all csv file in a specific folder.
I'm on OS X El Capitan version 10.11.6, and I'm using Python 2.7.10.
I have the following function in phyton file:
def open_csv_files(dir):
for root,dirs,files in os.walk(dir):
for file in files:
if file.endswith(".csv"):
f= open(file)
print "FILE OPEN, AND DO SOMETHING... "
f.close
return
I call open_csv_file(./dati/esempi)
This procedure return
IOError: [Errno 2] No such file or directory: 'sensorfile_1.csv'
I try to call the procedure with absolute path /Users/Claudia/Desktop/Thesis/dati/esempi/ but I have the same error.
Moreover I define another procedure that print all filename in folder, this procedure print correctly all filenames in folder.
Thanks for the help.
You need to build absolute path to file based on values of root (base dir) and file name.
import os
def open_csv_files(directory):
for root, dirs, files in os.walk(directory):
for file_name in files:
if file_name.endswith(".csv"):
full_file_path = os.path.join(root, file_name)
with open(full_file_path) as fh:
print "Do something with", full_file_path

Python finds a string in multiple files recursively and returns the file path

I'm learning Python and would like to search for a keyword in multiple files recursively.
I have an example function which should find the *.doc extension in a directory.
Then, the function should open each file with that file extension and read it.
If a keyword is found while reading the file, the function should identify the file path and print it.
Else, if the keyword is not found, python should continue.
To do that, I have defined a function which takes two arguments:
def find_word(extension, word):
# define the path for os.walk
for dname, dirs, files in os.walk('/rootFolder'):
#search for file name in files:
for fname in files:
#define the path of each file
fpath = os.path.join(dname, fname)
#open each file and read it
with open(fpath) as f:
data=f.read()
# if data contains the word
if word in data:
#print the file path of that file
print (fpath)
else:
continue
Could you give me a hand to fix this code?
Thanks,
def find_word(extension, word):
for root, dirs, files in os.walk('/DOC'):
# filter files for given extension:
files = [fi for fi in files if fi.endswith(".{ext}".format(ext=extension))]
for filename in files:
path = os.path.join(root, filename)
# open each file and read it
with open(path) as f:
# split() will create list of words and set will
# create list of unique words
words = set(f.read().split())
if word in words:
print(path)
.doc files are rich text files, i.e. they wont open with a simple text editor or python open method. In this case, you can use other python modules such as python-docx.
Update
For doc files (previous to Word 2007) you can also use other tools such as catdoc or antiword. Try the following.
import subprocess
def doc_to_text(filename):
return subprocess.Popen(
'catdoc -w "%s"' % filename,
shell=True,
stdout=subprocess.PIPE
).stdout.read()
print doc_to_text('fixtures/doc.doc')
If you are trying to read .doc file in your code the this won't work. you will have to change the part where you are reading the file.
Here are some links for reading a .doc file in python.
extracting text from MS word files in python
Reading/Writing MS Word files in Python
Reading/Writing MS Word files in Python

How best to display the content of a text file in python

Ok, I am abit of a python beginner. So, forgive me if this question sounds silly.
I have a directory that contains some .txt files as shown in the image below:
The 1.txt file contains :
Lo! I am lost.
I want to write a programme that goes through each file in the shakespeare directory and print out the content of the .txt file. Below is a programme I have written but I am not sure how to print out the content of each file. all it prints is the name of each file but how do I really print out the content of each file.
def readFromCorpus(path):
os.chdir(path)
for fu in glob.glob("*.txt"):
print fu
readFromCorpus('./trainingData/shakespeare')
I am sorry if this is really a silly question. I just need a pointer to what I am doing wrong.
Thanks
Try this:
def readFromCorpus(path):
os.chdir(path)
for fu in glob.glob("*.txt"):
print('\n\n'+fu)
with open(fu,'r') as f:
data = f.readlines()
for line in data:
print(line.replace('\n',''))

Creating and then writing to a file

So I want to read in a text file and then use some of that to write to another file that doesn't exist in the same directory. So for instance if I have a file named text.txt, I want to write a script that reads it and then creates another file, text2.txt which has some of its contents determined by what was in text.txt.
To read the file I'm using the command,
with open(inpath, 'r') as f:
...
But then what is the preferred way to create a new file and start writing to it? If I had to guess, I'd think it would be
with open(inpath, 'r') as f:
outtext = open(outpath, 'w')
...
where the variable outpath stores the directory of the file to be written. If I understand all this correctly, if the directory outpath happens to exist, running this script would destroy it or at least append to it. But if it doesn't exist, then Python would create the file. Is that accurate? And is there a better, more elegant way to do this?
I believe inpath and outpath are absolute paths. So you cannot do:
with open(inpath, 'r') as f:
...
It will throw IOError exception. open method expects a file path, but since you are providing path to a directory, exception occurs. The same applies to outpath also. Now Lets assume values of inpath and outpath as:
input_path = '/Users/avi/inputs'
output_path = '/Users/avi/outputs'
Now, to read a file, you could do:
input_file_path = os.path.join(input_path, 'input.txt')
The input_file_path will be now /Users/avi/inputs/input.txt
and to open this:
with open(input_file_path, 'r') as f:
...
Now coming to second question, yes, if file already exists python will overwrite. If it does not, it creates a new one. So you can first check whether file exists or not. If it does, then you can create a new one:
output_path_file = os.path.join(output_path, 'output.txt')
if os.path.isfile(output_path_file):
# file already exists
# do something else like create another file
output_path_file = os.path.join(output_path, 'new_output.txt')
# now write to output file
with open(output_file_path, 'w') as f:
...