【问题标题】:writing in a text file with [ ] python用 [ ] python 写入文本文件
【发布时间】:2016-08-23 09:11:35
【问题描述】:

我正在尝试用大括号写入文本文件。

output.write("{}\t{}\t{}\t{}\t{}\t".format(student_iD,user_id,First_name, Last_name,Other_name))
output.write("\n")

它在没有大括号的情况下写入文本文件。我应该添加什么才能得到这样的结果:

[student_id]  [user_id]  [First_name]  [Last_name]  [other_name] in the text file.

【问题讨论】:

  • 括号! 对不起,我很迂腐:考虑在花括号周围加上括号,比如[{}]。
  • 在将其内容写入文件之前,括号充当您应用到字符串的格式的占位符。将它们括在括号中以获得括号。
  • 在我的情况下它不起作用:(
  • @user3419487,它不工作如何??您尝试了哪些方法,遇到了哪些错误/不当行为?
  • 没有错误...但它只是在没有大括号的情况下打印。

标签: python python-2.7


【解决方案1】:

用[]包围这些大括号

output.write("[{}]\t[{}]\t[{}]\t[{}]\t[{}]\t".format(student_iD,user_id,First_name, Last_name,Other_name))
output.write("\n")

【讨论】:

    【解决方案2】:

    就这么简单:

    output.write("[{}]\t[{}]\t[{}]\t[{}]\t[{}]\t".format(...)
    

    或者在不改变格式字符串的情况下将括号括在变量名本身。然后您将打印列表,每个列表将仅包含一个值。

    output.write("{}\t{}\t{}\t{}\t{}\t".format([student_iD],[user_id], [First_name], [Last_name], [Other_name]))
    

    【讨论】:

    • @user3419487,你得到了什么输出?
    • 我得到了没有大括号的输出。 student_id user_id First_name Last_name other_name
    • @user3419487,不可能。你可能忘了close() 或flush() 输出。
    【解决方案3】:

    我的代码

    output = open('/home/vipul/Desktop/test_data.txt', 'a')
    output.write("[{}]\t[{}]\t[{}]\t[{}]\t[{}]\t".format(222,2222,'test',     'test','test'))
    output.write("\n")
    

    我得到的输出: [222] [2222] [测试] [测试] [测试]

    它的工作。如果您收到错误,请在此处粘贴您的输出。

    【讨论】:

    • output.write("[{}]\t[{}]\t[{}]\t[{}]\t{}\t".format([student_id],[ user_id],[First_name],[Last_name],Other_name)) output.write("\n") 输出我得到:26615188 0000-0002-9903-4248 Michael Baudis ['mbaudis']
    • 为什么还要在 format() 方法中给出 [ ]es ?只在一处提供。现在把它放在字符串中。并且一个大括号没有用大括号括起来。你得到什么输出?粘贴到这里。
    • 我已经尝试了各种......我猜还有一些其他问题
    • 我觉得很奇怪。我在我的机器上得到了你想要的准确输出。在 2.x 和 3.x 中。请粘贴运行代码时获得的输出。
    • 它适用于某些输出。但不是所有的。我得到的输出:['2014232'] ['0000-0002-3952-3285'] ['Des'] ['Higgins'] [['Des Higgins']]
    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 2014-06-16
    相关资源
    最近更新 更多