I'm trying to read a document and write it into a new file (that doesn't exist) in the same directory as the read file
An example would be
test_infile='/Users/name/Desktop/test.txt'
in_file=open(test_infile,'r')
data=in_file.readlines()
out_file=open('test_outfile.csv','w')
out_file should create a new file called test_outfile.csv in the directory /Users/name/Desktop/test_outfile.csv
I worked with the os module and got
def function(test):
import os
in_file=open(test,'r')
dir,file=os.path.split(test)
temp=os.path.join('output.csv')
out_file=open('output.csv','w')
test_file='/Users/name/Desktop/test.txt'
function(test_file)
it runs but nothing is created ?
Use the os.path.split
function to split the directory path from the file name, and then the os.path.join
function to stitch path constituents together:
import os
dir, file = os.path.split(test_infile)
out_file_name = os.path.join(dir, 'test_outfile.csv')
Please make sure you read the documentation of these functions, and the os.path
module in general, since it's very useful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.