Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
9 Trả lời
21146 Lượt xem

I placed a text file in the same directory as models.py and wrote a file opening and reading code in models.py to open and read the file content. I have set all permissions of the file properly as well. But the file is not read. I'm not sure whether it's a location error. The code works well independently (that means if the python code is run alone, not within odoo). Please help me in this...

Ảnh đại diện
Huỷ bỏ

Please add your code here so we can see what might be wrong with it.

Tác giả

I just found the solution for this Yenthe... thanks for the interest :) I'll add it as an answer

i already given you the test code. You can refer this link :- https://www.odoo.com/forum/help-1/question/load-external-file-script-via-action-button-click-93256

Tác giả Câu trả lời hay nhất

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.

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

The solution you found works in your computer, but it'll break if you try to use the module anywhere else. A better solution is to get the path of your module, then append the .txt file name:

def get_txt_path():
directory_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
return os.path.join(directory_path, 'filename.txt')

By the way, unless you have a good reason not to do so, I advise you to use "with open(...) as logFile:" instead of "logFile = open(...)", since it makes sure it'll always close the file, even if there's an exception. Otherwise, you might leak file handles.

Ảnh đại diện
Huỷ bỏ

I do agree with the statement from app. It is better to get the path of the module and then append, its more dynamic.

Tác giả

thank you for the information app (Y)... I'll change my code...

Tác giả

thank you for the information app (Y)... I'll change my code...

Câu trả lời hay nhất

Hello, please help i'm having the same problem and i did what u adviced but i still can't write the txt file,

im creating a module in odoo 8 , using ubuntu 18 and  docker.

this is my code :

from openerp import models, fields, api
import os

class odooimppn(models.Model):
    _name = 'odoo_imppn.content'
    _description = 'Odoo imppn content'

    def test(self):
        results = "this is a test to see if we are able to write on a text file located inside the module"
        path = os.path.expanduser('./etc/odoo/addons/odoo_imppn/IMPPN_tests.txt')
        fileIMPPN = open(path, 'r+')
        fileIMPPN.write(results)
        fileIMPPN.close()


test()

Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
3
thg 10 23
5966
2
thg 1 23
5346
Datetime in python Đã xử lý
7
thg 6 21
24668
11
thg 9 19
38471
0
thg 5 16
3914