-1

My teacher gave us a task: I gotta create 2 folders: folder1 folder2 And i gotta add a text file to folder1 then append asmthg on it (iknow i use f = open("//Folder1//text.txt", mode = a, encoding = "UTF-8) then f.append("Hello World!") and then i gotta copy the text file in folder1 to folder2 as text.txt(Copy) without using shutil.copyfile

So can anyone help about it?

  • You can read the context of the file (using `open`) and then you can write the same content in a new file in folder 2 (again, open it with the `open` built-in function) – Riccardo Bucco Mar 05 '22 at 17:41
  • Does this answer your question? [how to copy files in python without os.rename and shutil library?](https://stackoverflow.com/questions/69423254/how-to-copy-files-in-python-without-os-rename-and-shutil-library) – LeopardShark Mar 05 '22 at 17:46

1 Answers1

1

If you have a .txt file you can always read it this way:

with open("file.txt", 'r') as file:
    content = file.read()

and write to a file this way:

with open("otherfile.txt", 'w') as otherfile:
    otherfile.write(content)

So this is the easier way to duplicate a file, since open with option 'w' (write mode) will automatically create the file if it doesn't exist.


In your case, since you have paths like r'\\Folder1\\text.txt' you just have to replace "file.txt" with your path, this way:

with open("\\Folder1\\text.txt", 'r') as file:
    ...
with open("\\Folder2\\text.txt", 'w') as newfile:
    ...
FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28