首页 \ 问答 \ 麻烦的Python操作/循环顺序(Trouble with Python order of operations/loop)

麻烦的Python操作/循环顺序(Trouble with Python order of operations/loop)

我有一些代码用于将CSV文件转换为制表符分隔文件。 我的问题是我无法弄清楚如何以正确的顺序写出正确的值。 这是我的代码:

for file in import_dir:
    data = csv.reader(open(file))
    fields = data.next()
    new_file = export_dir+os.path.basename(file)
    tab_file = open(export_dir+os.path.basename(file), 'a+')
    for row in data:
        items = zip(fields, row)
        item = {}
        for (name, value) in items:
            item[name] = value.strip()
    tab_file.write(item['name']+'\t'+item['order_num']...)
    tab_file.write('\n'+item['amt_due']+'\t'+item['due_date']...)

现在,由于我的两个write语句都在for row in data循环中的for row in data ,因此我的头文件被多次写入。

如果我突然出现第一个write语句,我将会出现明显的格式错误。
如果我将第二个write语句移到第一个然后突出的上面,我的数据就会出现故障。

我该怎么做才能确保第一个write语句作为标题写入一次,第二个写入为CSV文件中的每一行写入? 如何在不破坏字典的情况下在循环外提取第一个'write'语句? 谢谢!


I have some code that is meant to convert CSV files into tab delimited files. My problem is that I cannot figure out how to write the correct values in the correct order. Here is my code:

for file in import_dir:
    data = csv.reader(open(file))
    fields = data.next()
    new_file = export_dir+os.path.basename(file)
    tab_file = open(export_dir+os.path.basename(file), 'a+')
    for row in data:
        items = zip(fields, row)
        item = {}
        for (name, value) in items:
            item[name] = value.strip()
    tab_file.write(item['name']+'\t'+item['order_num']...)
    tab_file.write('\n'+item['amt_due']+'\t'+item['due_date']...)

Now, since both my write statements are in the for row in data loop, my headers are being written multiple times over.

If I outdent the first write statement, I'll have an obvious formatting error.
If I move the second write statement above the first and then outdent, my data will be out of order.

What can I do to make sure that the first write statement gets written once as a header, and the second gets written for each line in the CSV file? How do I extract the first 'write' statement outside of the loop without breaking the dictionary? Thanks!


原文:https://stackoverflow.com/questions/16845878
更新时间:2021-10-20 17:10

最满意答案

您可以使用setInterval方法在每个固定时间延迟上调用函数,在大多数情况下,它将与clearInterval方法一起用于停止重复调用,这里是一个示例:

var interval = setInterval( function () {
    afoo( function (err) {
        // clear interval if an error occured
        if ( err ) {
            console.log(err);
            clearInterval(interval);
        }
    });
}, 5 * 60 * 1000);

如果你想要更多的控制,那么使用node-cron模块,它与linux系统使用的cron模式相同,例如:

const CronJob = require('cron').CronJob;

// run afoo function every 15 min
var job = new CronJob('00 15 * * * *', afoo);

You could use setInterval method to call a function on every fixed time delay, in the most case it's used in conjunction with clearInterval method to stop the repeated calls, here is an example:

var interval = setInterval( function () {
    afoo( function (err) {
        // clear interval if an error occured
        if ( err ) {
            console.log(err);
            clearInterval(interval);
        }
    });
}, 5 * 60 * 1000);

If you want more control then use node-cron module, it has the same cron pattern used by linux systems, Example:

const CronJob = require('cron').CronJob;

// run afoo function every 15 min
var job = new CronJob('00 15 * * * *', afoo);

相关问答

更多
  • JVM上的nanoTime被认为是安全的,但不是很准确。 这里有一些很好的读物: System.nanoTime()完全没用吗? System.currentTimeMillis vs System.nanoTime 基本上你的测试会受到计时器不准确的影响。 解决这个问题的一种方法是time("outerpos")调用time("outerpos") (注意JIT编译器优化可能会在某个时刻启动)并仅测量一次开始和结束时间。 取平均值并重复time("innerpos") 。 这就是我所能想到的。 仍然不是有 ...
  • 我建议您查看内置的Python剖析器( profile或cProfile ,具体取决于您的需求): http : cProfile Instead of writing your own profiling code, I suggest you check out the built-in Python profilers (profile or cProfile, depending on your needs): http://docs.python.org/library/profile.html
  • 正如Mark Rejhon的回答中所提到的,现代浏览器中提供了一个API,可以将亚毫秒分辨率时序数据暴露给脚本: W3C高分辨率定时器 ,即window.performance.now() 。 now()比传统的Date.getTime()有两个重要的方面: now()是一个双倍的亚毫秒分辨率,代表页面导航开始以来的毫秒数。 它返回分数的微秒数(例如,1000.123的值为1秒和123微秒)。 now()单调增加。 这很重要,因为Date.getTime() 可能在后续调用时向前或向后跳转。 值得注意的是, ...
  • 您将返回once()函数,而不是promise链。 基本上,你写的是这样的: //returns the once promise return ref.once('value', function(snap) { /* some stuff that doesn't affect the promise chain happens here */ }); 当你想要的是这样的: // returns whatever happens in the .then() callback return re ...
  • 您可以使用setInterval方法在每个固定时间延迟上调用函数,在大多数情况下,它将与clearInterval方法一起用于停止重复调用,这里是一个示例: var interval = setInterval( function () { afoo( function (err) { // clear interval if an error occured if ( err ) { console.log(err); ...
  • 您可以使用命令分组而不是子shell: time { command1; command2; } 更新 - 更具体的示例: test-function() { time { rsync -av ~/tmp/test-dir-start/ ~/tmp/test-dir-end/ rsync -av ~/tmp/test-dir-start/ ~/tmp/test-dir-end-2/ # etc... } } You can use command grou ...
  • 如评论中所示,性能计时插件使用s.performanceTiming(); 触发实际的插件。 这就是说它应该如何配置才能正常工作。 s.pte是用于确定是否执行实际插件的调用。 `s.pte = 'event10,event11,event12,event13,event14,event15,event16,event17,event18,event19' //[--------------------------- 1 to 8 ---------------------------][-- 9 --][ ...
  • 我通常使用Windows hihg分辨率性能计数器。 查看QueryPerformanceCounter和QueryPerfomanceFrequency 通常我有一个简单的类,其构造函数和析构函数调用QueryPerformanceCounter,然后将差异添加到运行总计。 对于工具,请查看devpartner 。 虽然它运行良好,但检测大量代码会使我的应用程序运行速度极慢。 我通常发现我希望只在一两个函数上得到精确的时序,所以我经常最终使用性能计数器函数而不是使用devpartner。 I typica ...
  • 您只能使用命令行客户端psql使用\timing ,因为这是一个psql命令。 它是一个开关,可以打开和关闭执行时间报告: test=> \timing Timing is on. test=> SELECT 42; ┌──────────┐ │ ?column? │ ├──────────┤ │ 42 │ └──────────┘ (1 row) Time: 0.745 ms test=> \timing Timing is off. You can use \timing only wi ...
  • 你可以做的一件事是将一个设置超时放在另一个设置中。 现在你有setTimeout(,时间); setTImeout(,time * 2); setTImeout(,time * 3); 也许如果你把它改成:setTimeout(... setTimeout(... setTimeout(...,time),time),time); 所以这将确保执行顺序。 第一个将永远执行。 One thing that you can do is put one set timeout inside another one ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。