如何将列表列表写入文件

时间:2017-12-16 11:41:21

标签: python list file-io file-writing

我有一个看起来像这样的列表

list_geo = [[5], ['Optimized energy: -39.726863484331 E_h'],
    ['C\t', '-1.795202\t', ' 0.193849\t', ' 0.019437'],
    ['H\t', '-0.728046\t', '0.337237\t', ' 0.135687'],
    ['H\t', '-2.044433\t', '-0.840614\t', ' 0.220592'],
    ['H\t', '-2.085087\t', ' 0.444715\t', '-0.993886'],
    ['H\t', '-2.323267\t', ' 0.834105\t', ' 0.714902']]

我想将此内容写入文件outputfile,我尝试使用

with open(outputfile, "w") as output_file:
    output_file.write(list_geo)

但这不起作用。加入list_geo也不起作用。我怎么能保存这个?

3 个答案:

答案 0 :(得分:1)

您需要使用for循环

with open("path /of/op/file.txt", "w") as output_file:
   for value in list_geo:
       output_file.write(str(value))

答案 1 :(得分:0)

您无法直接将列表写入文件,但您可以编写字符串/字符流。

将列表转换为字符串,然后将字符串写入文件

data = ['1','2'] 
data_string = ','.join(data) # create string and then store

with open('f.txt','w') as f:
        f.write(data)

答案 2 :(得分:0)

我想将列表中的每个子列表都写成一行。

然后这就是你需要的:

list_geo = [[5], ['Optimized energy: -39.726863484331 E_h'],
    ['C\t', '-1.795202\t', '0.193849\t', '0.019437'],
    ['H\t', '-0.728046\t', '0.337237\t', '0.135687'],
    ['H\t', '-2.044433\t', '-0.840614\t', '0.220592'],
    ['H\t', '-2.085087\t', '0.444715\t', '-0.993886'],
    ['H\t', '-2.323267\t', '0.834105\t', '0.714902']]

with open("file.txt", "w") as output_file:
   for line in list_geo:
       output_file.write("".join([str(i) for i in line]))
       output_file.write("\n")

运行脚本后file.txt的内容:

5
Optimized energy: -39.726863484331 E_h
C       -1.795202       0.193849       0.019437
H       -0.728046       0.337237       0.135687
H       -2.044433       -0.840614      0.220592
H       -2.085087       0.444715       -0.993886
H       -2.323267       0.834105       0.714902

说明:

  • "".join()获取一个字符串列表,只是将它们连接在一起,而
  • 之间没有空格
  • [str(i) for i in line]会将列表中的每个元素转换为字符串(只需要[5]作为列表中的第一个子列表)
  

有没有办法保留正数的额外空间?

如果你想为你的行添加格式,你最好先将值作为实数,即代替['C\t', '-1.795202\t', ' 0.193849\t', ' 0.019437'],你需要['C', -1.795202, 0.193849, 0.019437],然后用例如"{}\t{:>9f}\t{:>9f}\t{:>9f}\n".format(*line)格式化它们。 list_geo = [[5], ['Optimized energy: -39.726863484331 E_h'], ['C\t', '-1.795202\t', '0.193849\t', '0.019437'], ['H\t', '-0.728046\t', '0.337237\t', '0.135687'], ['H\t', '-2.044433\t', '-0.840614\t', '0.220592'], ['H\t', '-2.085087\t', '0.444715\t', '-0.993886'], ['H\t', '-2.323267\t', '0.834105\t', '0.714902']] with open("file.txt", "w") as output_file: for line in list_geo: if len(line) == 4: # treat first element as string, convert rest to float line = [el.strip() if i == 0 else float(el) for i,el in enumerate(line)] line_formatted = "{}\t{:>9f}\t{:>9f}\t{:>9f}\n".format(*line) output_file.write(line_formatted) else: output_file.write("".join([str(i).strip(" ") for i in line])) output_file.write("\n")

如果你以某种方式从脏源获取此列表而无法更改,那么您需要以某种方式预处理该行,例如像这样:

5
Optimized energy: -39.726863484331 E_h
C       -1.795202        0.193849        0.019437
H       -0.728046        0.337237        0.135687
H       -2.044433       -0.840614        0.220592
H       -2.085087        0.444715       -0.993886
H       -2.323267        0.834105        0.714902

结果是:

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Workbook xlWorkBookahan1;
            Excel.Workbook xlWorkBookahan2;
            Excel.Workbook xlWorkBookahangh;
            Excel.Worksheet xlWorkSheet;
            Excel.Worksheet xlWorkSheetahan1;
            Excel.Worksheet xlWorkSheetahan2;
            Excel.Worksheet xlWorkSheetahangh;
            Excel.Range range;

            string str;
            int rCnt;
            int cCnt;
            int rw = 0;
            int cl = 0;

            //
            Excel.Application xlahan1 = new Microsoft.Office.Interop.Excel.Application();
            Excel.Application xlahan2 = new Microsoft.Office.Interop.Excel.Application();
            Excel.Application xlahangh = new Microsoft.Office.Interop.Excel.Application();
            object misValue = System.Reflection.Missing.Value;


            if (xlahan1 == null)
            {
                MessageBox.Show("Excel is not properly installed!!");
                return;
            }
            xlWorkBookahan1 = xlahan1.Workbooks.Add(misValue);
            xlWorkBookahan2 = xlahan2.Workbooks.Add(misValue);
            xlWorkBookahangh = xlahangh.Workbooks.Add(misValue);
            xlWorkSheetahan1 = (Excel.Worksheet)xlWorkBookahan1.Worksheets.get_Item(1);
            xlWorkSheetahan2 = (Excel.Worksheet)xlWorkBookahan2.Worksheets.get_Item(1);
            xlWorkSheetahangh = (Excel.Worksheet)xlWorkBookahangh.Worksheets.get_Item(1);


            //

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\maedeh\Desktop\Base.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            range = xlWorkSheet.UsedRange;
            rw = range.Rows.Count;
            cl = range.Columns.Count;

            int ahanghtei = 0, ahan1 = 0, ahan2 = 0, fooladghatei = 0, foolad1 = 0, foolad2 = 0, ngarmghatei = 0, ngarm1 = 0, ngarm2 = 0, nsardghatei = 0, nsard1 = 0, nsard2 = 0, energyghatei = 0, energy1 = 0, energy2 = 0, hamlghatei = 0, haml1 = 0, haml2 = 0, tmarkazighatei = 0, tmarkazi1 = 0, tmarkazi2 = 0, tgmarkazighatei = 0, tgmarkazi1 = 0, tgmarkazi2 = 0, dfnetghatei = 0, dfnet1 = 0, dfnet2 = 0, mtnasoozghatei = 0, mtnasooz1 = 0, mtnasooz2 = 0, fooladsabaghatei = 0, fooladsaba1 = 0, fooladsaba2 = 0;

            for (rCnt = 2; rCnt <= rw; rCnt++)
            {
                if (range.Cells[rCnt, 25].value == 1)//
                {
                        if (((range.Cells[rCnt, 16]).value <= 1999 && (range.Cells[rCnt, 16]).value >= 1000))
                  {
                      if ((range.Cells[rCnt, 120]).value >= 1000 && (range.Cells[rCnt, 120]).value <= 1999)
                      {
                          ahanghtei++;
                          xlWorkSheetahangh.Cells[ahanghtei, 1] = range.Cells[rCnt, 1];
                          xlWorkSheetahangh.Cells[ahanghtei, 2] = range.Cells[rCnt, 2];
                          xlWorkSheetahangh.Cells[ahanghtei, 3] = range.Cells[rCnt, 3];
                      }
                      else
                      {
                          xlWorkSheet.Rows[rCnt].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                          ahan1++;
                          xlWorkSheetahan1.Cells[ahan1, 1] = range.Cells[rCnt, 1];
                          xlWorkSheetahan1.Cells[ahan1, 2] = range.Cells[rCnt, 2];
                          xlWorkSheetahan1.Cells[ahan1, 3] = range.Cells[rCnt, 3];
                      }
                  }
                  else
                  {
                      if ((range.Cells[rCnt, 120]).value >= 1000 && (range.Cells[rCnt, 120]).value <= 1999)
                      {
                          xlWorkSheet.Rows[rCnt].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                          //xlWorkSheet.Cells[rCnt, 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                          ahan2++;
                          xlWorkSheetahan2.Cells[ahan2, 1] = range.Cells[rCnt, 1];
                          xlWorkSheetahan2.Cells[ahan2, 2] = range.Cells[rCnt, 2];
                          xlWorkSheetahan2.Cells[ahan2, 3] = range.Cells[rCnt, 3];

                      }
                  }

xlWorkBookahan1.SaveAs("C:\\ahan1.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBookahan2.SaveAs("C:/Users/maedeh/Desktop/ahan2.xls");
            xlWorkBookahangh.SaveAs("C:/Users/maedeh/Desktop/ahangh.xls");
            xlWorkBookahan1.Close(true, misValue, misValue);
            xlWorkBookahan2.Close(true, misValue, misValue);
            xlWorkBookahangh.Close(true, misValue, misValue);
            xlahan1.Quit();
            xlahan2.Quit();
            xlahangh.Quit();

            Marshal.ReleaseComObject(xlWorkSheetahan1);
            Marshal.ReleaseComObject(xlWorkSheetahan2);
            Marshal.ReleaseComObject(xlWorkSheetahangh);
            Marshal.ReleaseComObject(xlWorkBookahan1);
            Marshal.ReleaseComObject(xlWorkBookahan2);
            Marshal.ReleaseComObject(xlWorkBookahangh);
            Marshal.ReleaseComObject(xlahan1);
            Marshal.ReleaseComObject(xlahan2);
            Marshal.ReleaseComObject(xlahangh);

            Marshal.ReleaseComObject(range);
            Marshal.ReleaseComObject(xlWorkSheet);

            //close and release
            xlWorkBook.Close();
            Marshal.ReleaseComObject(xlWorkBook);

            //quit and release
            xlApp.Quit();
            Marshal.ReleaseComObject(xlApp);