0

I'm try to write some data into new files in new folder,but there is nothing in new files

Use Debian linux Python3.6.8 I'm trying read data from file in folder and write to the other new create folder and create file.

import os 
openfolder='testforopen'
path=os.getcwd()+'/testforopen'
os.chdir(path)
file_open=open('test.txt',mode='r')
file_read=file_open.read()
os.chdir('..')
createfolder='testforcreate'
os.mkdir(createfolder)
os.chdir(createfolder)
file_create=open('dst.txt',mode='w',encoding='utf-8')
file_create.write = (file_read+ '\n')
file_create.close()
file_open.close()

============ import os

there is no error msg

  • `.write =` doesn't call the `file.write` member function, it replaces it. – Peter Wood Aug 07 '19 at 14:12
  • It looks like you just want to copy the file. Use [**`shutil.copy`**](https://docs.python.org/3/library/shutil.html#shutil.copy) or similar. See https://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python – Peter Wood Aug 07 '19 at 14:14
  • Unrelated to question, but two things: 1. `path=os.getcwd()+'/testforopen'`, don't do that, join them using `os.path.join()`, it will do it in a sane manner and will almost always (if not definitely always) prevent unexpected issues related to paths. 2. you don't need to change directory, you can just write a file into `../file.txt` and it will write a file in parent directory. It's better to stay inside one working directory and use absolute or relative paths depending on your needs, the latter becomes simpler to deal with, as there's only one directory you can be in at any given time. –  Aug 07 '19 at 17:24

1 Answers1

1

Try to replace :

file_create.write = (file_read+ '\n')

By :

file_create.write(file_read+ '\n')
Alex_6
  • 259
  • 4
  • 16