Python File Input/Output

Asked 2 years ago, Updated 2 years ago, 15 views

I don't understand file input/output well...]\

filename = input ("input filename: ") outfilename = input ("output filename: ")

infile = open(infilename, "r") outfile = open(outfilename, "w")

s = infile.read()

outfile.write(s)

infile.close() outfile.close()

Which part is wrong? Running results in an error Da

python

2022-09-21 23:12

2 Answers

import os

path = os.getcwd(); #Save the current path (directory)

full_path = path + '/test.txt' #current path + filename

###################### Write a file ############################################

try:
    file1 = open(full_path, mode='w') #mode = 'a' : earwriting // mode = 'w' : new writing

    file1.write("Hello") #Write to File

    file1.close()

except Exception as err:
    print(str(err))

####################### Read the file ##########################################

try:
    file1 = open(full_path, mode='r') #mode = 'r' : read

    text = file1.read() #Read from file and save to text variable

    print(text)

    file1.close()

except Exception as err:
    print(str(err))

Instead of just writing the file name in the first parameter of open, you have to combine the file names in the entire path

**Correction As Kei answered, if you call open by writing only the file name, check if there is a file to open in the folder with the Python code that you are currently running, and open it if there is one. Therefore, even if you use an absolute path, if you specify mode as r, the file must exist in that path. You should always try~exception in case the file does not exist.


2022-09-21 23:12

In general, the file input/output function has a default value for the location where you are working (the script file is open). To open a file, you can convert it to an absolute value, as described above, and make sure that the file you are currently working with is in the same location as the source code.


2022-09-21 23:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.