【问题标题】:can't see the file created in python看不到在python中创建的文件
【发布时间】:2018-06-02 06:12:43
【问题描述】:
    def _store_file(self, logVal):
        if not os.path.exists('logs'):
            print("[INFO] creating directory")
            a = os.makedirs("logs")
            print("INFO create Dir result: " + str(a))
         f = None
        try:
            print("{INFO} Trying to open the file for writing logs")
            f = open(self.conf['filename'], 'w')
            print("{INFO} realpath of file is: " + os.path.realpath(f.name))
            print("{INFO} abs path of file is: " + os.path.abspath(f.name))
            res = f.write(str(logVal))
            print("INFO file write: " + str(res))
        except IOError as er:
            print("[INFO]" + str(er))
        finally:
            f.close()
        print("[INFO] WRITTING TO FILE")
        print("sdfjsbdfkjbsdfkjbskjdfbskjfbskjbfkjsdbsdfksds",file=open('logs/temp.txt', 'w'))

我编写了一个中间件,它将请求数据发送到一个模块,该模块将日志存储在文件夹日志内的文件 debug.log 中。写入文件的代码没有给出任何错误,但我看不到任何名为 log 的文件夹或任何名为 debug.log 的文件。此外,当我尝试查看它提供的文件的完整路径时

/code/logs/debug.log

我已经搜索了整个系统,但找不到这条路径

上述代码的输出是:

web_1  | [EventTracker INFO]: log sent for storage
web_1  | [INFO] present working directory: .  
web_1  | [INFO] creating directory
web_1  | INFO create Dir resutl: None
web_1  | {INFO} Trying to open the file for writing logs
web_1  | {INFO} realpath of file is: /code/debug.log
web_1  | {INFO} abs path of file is: /code/debug.log
web_1  | INFO file write: 432
web_1  | [INFO] WRITTING TO FILE
web_1  | [02/Jun/2018 06:39:16] "GET /community-view/1/ HTTP/1.1" 200 17353
web_1  | [EventTracker.sendRequestData INFO] new data object added to bucket

【问题讨论】:

  • 您能否提供脚本的输出(即{INFO} 语句)?
  • 而不是使用f = open('logs/' + self.conf['filename'], 'w'),使用os.path.join()
  • @a874 我正在使用 docker 运行它,以便它可以在虚拟环境中运行。所以我认为问题是别的
  • 使用绝对路径名而不是相对于当前目录的名称。
  • 有点不相关,但是当 Python 的 stdlib 带有一个完全开发的日志包时,你到底为什么要重新发明方轮呢?

标签: python django file-io


【解决方案1】:

查看您的代码,我认为您正在尝试定义一个私有方法来将对象存储到文件中。

In [   ]: class My_Object(object):
     ...:     conf = {}
     ...: 
     ...:     def __init__(self):
     ...:         self.conf['filename'] = "filename.txt"    
     ...: 
     ...:     def _store_file(self, logVal):
     ...:         if not os.path.exists('logs'):
     ...:             print("[INFO] creating directory")
     ...:             a = os.makedirs("logs")
     ...:             print("INFO create Dir result: " + str(a))
     ...:         f = None
     ...:         try:
     ...:             print("{INFO} Trying to open the file for writing logs")
     ...:             f = open('logs/' + self.conf['filename'], 'w')
     ...:             print("{INFO} realpath of file is: " + os.path.realpath(f.name))
     ...:             print("{INFO} abs path of file is: " + os.path.abspath(f.name))
     ...:             res = f.write(str(logVal))
     ...:             print("INFO file write: " + str(res))
     ...:         except IOError as er:
     ...:             print("[INFO]" + str(er))
     ...:         finally:
     ...:             f.close()
     ...:         print("[INFO] WRITTING TO FILE")
     ...: 

In [145]: Test_Instance = My_Object()

In [146]: Test_Instance._store_file("This is a test")
[INFO] creating directory
INFO create Dir result: None    # because os.makedirs do not return value
{INFO} Trying to open the file for writing logs
{INFO} realpath of file is: xxxxxxx
{INFO} abs path of file is: xxxxxxx
INFO file write: None    # because f.write() returning None object
[INFO] WRITTING TO FILE

快速浏览logs/filename.txt的内容:

This is a test

打印出来的值显示 None 有两个原因。第一件事是:

f.write(string) 将字符串的内容写入文件,返回 没有。

第二件事是:

os.makedirs()此方法不返回任何值。

我修复代码的版本:

In [   ]: class My_Object(object):
     ...:     conf = {}
     ...: 
     ...:     def __init__(self):
     ...:         self.conf['filename'] = "filename.txt"    
     ...: 
     ...:     def _store_file(self, logVal):
     ...:         save_dir = 'logs'    # use indirection instead
     ...:         if not os.path.exists(save_dir):
     ...:             print("[INFO] creating directory")
     ...:             os.makedirs(save_dir)
     ...:             print("INFO create Dir result: " + str(save_dir))
     ...:             
     ...:         f = None
     ...:         try:
     ...:             print("{INFO} Trying to open the file for writing logs")
     ...:             f = open('logs/' + self.conf['filename'], 'w')
     ...:             print("{INFO} realpath of file is: " + os.path.realpath(f.name))
     ...:             print("{INFO} abs path of file is: " + os.path.abspath(f.name))
     ...:             f.write(str(logVal))    # Assignment not necessary
     ...:             print("INFO file write: " + str(logVal))    # directly print logVal since it is the content you want to show
     ...:         except IOError as er:
     ...:             print("[INFO]" + str(er))
     ...:         finally:
     ...:             f.close()
     ...:         print("[INFO] WRITTING TO FILE")
     ...: 

In [   ]: Test_Instance = My_Object()

In [   ]: Test_Instance._store_file("This is a test")
{INFO} Trying to open the file for writing logs
{INFO} realpath of file is: xxxxxx
{INFO} abs path of file is: xxxxxx    
INFO file write: This is a test
[INFO] WRITTING TO FILE

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-02
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多