'python Cannot write file when import module function
I created a module "test" with these code:
def write_file():
with open("testw.txt", 'w') as t:
t.writelines("test ok")
print(t)
if import from other module and run below code:
import test
test.write_file()
it can print out: <_io.TextIOWrapper name='testw.txt' mode='w' encoding='cp950'> but the file cannot create!
If i run write_file() in test module, it can create the file just fine, how can i write the file while the write file code is import from other module?
Solution 1:[1]
Um there are 2 ways you could do it i guess.
First:
Create a different folder called test_module and add the test.py file into the directory. Also ad a blank init.py file to the folder.
so if you do this,
import test_module
test_module.test.write_file()
or...
from test_module import test
test.write_file()
It should probably work
The second way is this
import .test as test
test.write_file()
you could also do this
from .test import write_file
write_file()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aaseer |
