将for循环的输出写入与文件名相同的多个文件作为输入文件

时间:2017-02-02 10:15:17

标签: python python-2.7

我在文件filenames.txt中有一个文件名列表。我将逐个打开所有文件,并希望将某些操作的结果写入不同的目录,但文件名相同。到目前为止,我试过这个,但这不会奏效。有什么帮助吗?

with open("/home/morty/filenames.txt","r") as f:
    names = [name.strip() for name in f]

for name in names:
    save=open("/home/morty/dir/%name" %name,"w")
    save.write(---some operation---)

我的问题与此类似,但我不想要通过count / enumerate命名的文件。我希望名称与输入文件名相同: Write output of for loop to multiple files

1 个答案:

答案 0 :(得分:1)

您的格式声明不正确。它应该是var webpack = require('webpack'); var webpackDevServer = require('webpack-dev-server'); var webpackConfig = require('../webpack.config.js'); var path = require('path'); var fs = require('fs'); var mainPath = path.resolve(__dirname, '..', 'resources/assets/scripts', 'main.js'); module.exports = function() { // Fire webpack and run compiler var bundleStart = null; var compiler = webpack(webpackConfig); // Notify console that bundling started compiler.plugin('compile', function() { console.log('Bundling...'); bundleStart = Date.now(); }); // Notify when compiling is done compiler.plugin('done', function() { console.log('Bundled in ' + (Date.now() - bundleStart) + 'ms!'); }); // Init instance of webpackDevServer var bundler = new webpackDevServer(compiler, { publicPath: '/public/', hot: true, quiet: false, noInfo: true, stats: { colors: true } }); // Start development server and give some notifications in console bundler.listen(8080, 'localhost', function() { console.log('Bundling project, please wait...'); }); }

但是当你想加入一个带有文件名的目录名时,最好是这样使用"/home/morty/dir/%s" %name

os.path.join

(以及for name in names: with open(os.path.join("/home/morty/dir",name),"w") as save: save.write(---some operation---) 上下文块,以确保文件在完成后关闭)