[英]Write to new non-existent file in same directory, Python 2.7
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 out_file应该在目录/Users/name/Desktop/test_outfile.csv中创建一个名为test_outfile.csv的新文件。
I worked with the os module and got 我使用os模块并得到了
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: 使用
os.path.split
函数将目录路径与文件名分开,然后使用os.path.join
函数将路径组成部分缝合在一起:
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. 请确保您阅读了这些功能的文档以及
os.path
模块,因为它非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.