1

Please I am not looking for this. How do I copy a file in Python? I got this file to save but I don't know how to go about it. With the code below I am able to save the text in the data variable. How can I code it so that the data variable points to a document in my directory which I'd like to re-save in another selected location?

a = QFileDialog.getSaveFileName(MainWindow, "Save results", os.getenv("HOME"), "Save pdf(*.pdf);;Save csv(*.csv);;Save excel(*.xlsx);;Save text(*.txt)")
    name = open(a[0],'w')
    data = "This is my text"
    name.write(data)
    name.close()
Ptar
  • 374
  • 4
  • 16

3 Answers3

1

You can use a context manager for this:

# Choose the new path for your file, example: r'Desktop\my_file.txt'
new_file_path = input("Location to store new file: ")


# use mode = 'a' to append to file, mode = 'w' to overwrite

with open(a[0], 'r') as read_file, open(new_file_path, 'a') as write_file:
    data = read_file.readlines()
    new_file_path.write(data)
Gustav Rasmussen
  • 3,720
  • 4
  • 23
  • 53
  • 1
    Passing a filename in the bracket will work it out? – Ptar May 23 '20 at 11:50
  • It depends on the nature of your a object, but in principle yes. I can check it for you if you provide further description of the a-object. But Pythons context-managers are ideal for this type of task, and handles closing of file after working with it automatically. – Gustav Rasmussen May 23 '20 at 11:52
  • Assuming that a[0] is a valid filename and format (e.g. "my_file.txt"), the code I provided will work – Gustav Rasmussen May 23 '20 at 11:53
  • You can inspect the file first, by the command: print(f"{a[0] = }") – Gustav Rasmussen May 23 '20 at 11:55
1

Looks like you just want to copy the contents of the file, or even add some to the new one. Just get all the lines, do whatever you want with them, and save them to another file.

Just be cautious, if the file is too large, it's not a good practice to load it all in memory, you could do this iteratively, by reading and writing line by line.

with open(a[0],'w') as infile:
    lines = infile.readlines()

with open('newfilename', 'wb') as outfile:
    outfile.writelines(lines)
stavrosfil
  • 36
  • 3
0

Thanks all who gave an attempt to my question. I was able to combine both and I finally figured out what I wanted. The solution I got was.

with open(a[0], 'w') as user_file_name:
    user_file_name.writelines(open(the_existing_file_to_save))
Ptar
  • 374
  • 4
  • 16