简体   繁体   English

此“文件打开”代码有什么问题?

[英]What is wrong with this “file Open” code?

I am not able to open an excel file to write data using following code in python 2.7.3. 我无法使用python 2.7.3中的以下代码打开Excel文件来写入数据。 What is wrong with this code? 此代码有什么问题?

def openfile():
    import os
    f=open('ab.xls', 'w')
    return

import Tkinter
from Tkinter import *
root=Tk()
root.geometry('100x100+100+100')

button1=Button(root, text='Open file', command=openfile)
button1.pack()

root.mainloop()

Thanks 谢谢

  1. Putting import os inside the function means it doesn't get imported until you run the function... probably not what you want. import os函数中意味着它只有在运行该函数后才能被导入……可能不是您想要的。

  2. You open the file, but never return a handle to it. 您打开文件,但不要返回它的句柄。 Try replacing return with return f 尝试用return f替换return

  3. If you are using import xlwt , you don't need this anyway; 如果您正在使用import xlwt ,那么无论如何您都不需要这样做。 it takes care of writing to a file. 它负责写入文件。 See my previous response at How to export user inputs (from python) to excel worksheet? 请参阅我以前的回答, 如何将用户输入(从python)导出到excel工作表?

Edit: 编辑:

... 'ab.xls' was opened, you returned a handle to it, and then do nothing with it . ...'ab.xls'已打开,您返回了它的句柄,然后对其不执行任何操作 What did you expect it to do, exactly? 您究竟希望它做什么?

Try 尝试

import Tkinter as tk

def do_something_with_file():
    with open('ab.xls', 'w') as f:
        print("The file is open")
        # --> now DO SOMETHING with it <--

root = tk.Tk()
root.geometry('100x100+100+100')
button1 = tk.Button(root, text='Open file', command=do_something_with_file)
button1.pack()
root.mainloop()

You seem to be confused about what open means in this context. 在这种情况下,您似乎对开放意味着什么感到困惑。 open() is a function that returns a file handle in Python so you can read the data into your application. open()是一个返回Python中文件句柄的函数,因此您可以将数据读入应用程序。

If you want to open the file with the default program on your system for that filetype, look into os.startfile() . 如果要使用系统上默认程序打开该文件类型的文件,请查看os.startfile()

Your "f" variable is a file object that is a local variable (destroyed as soon as the "openfile" function ends). 您的“ f”变量是一个文件对象,它是一个局部变量(“ openfile”函数结束后立即销毁)。 You can either declare f as global, or have your openfile function return the file object. 您可以将f声明为全局,也可以让openfile函数返回文件对象。

i can't see any obvious fatal errors in this code. 我在此代码中看不到任何明显的致命错误。

going out on a limb here, especially if you are running this on windows, is the file perhaps still open somewhere else, like in excel or through your own code? 尤其是在Windows上运行时,文件可能还在打开,例如在excel中还是通过您自己的代码打开了? you can not open a file for writing if it already is open for writing elsewhere. 如果文件已经可以在其他地方写入,则无法打开该文件进行写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM