如何用python将九九乘法表写入csv文件中?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用python将九九乘法表写入csv文件中?相关的知识,希望对你有一定的参考价值。

就是下图这样的形式

参考技术A

方法/步骤

    首先创建一个csv_scripts.py文件来保存我们的脚本,如下面图中所示:

    请点击输入图片描述

    然后编辑脚本内容如下:

    import csv

    # 打开一个csv文件对象

    with open('test.csv','w', newline='') as csvfile:

    # 创建一个写入对象

    spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

    #向csv文件里写入第一行

    spamwriter.writerow(['spam']*5 + ['Baked Beans'])

    # 向csv文件里写入第二行

    spamwriter.writerow(['spam', 'Lovely Spam', 'Wonderful Spam'])

    请点击输入图片描述

    脚本内容编辑好以后,对应的解释内容都在#号注释后面,通过导入csv模块,然后打开一个test.csv文件对象,然后调用csv模块里的writer函数,返回一个writer对象 spamwriter,然后这个spamwriter对象就有了可以写入csv文件的能力。给它的writerow函数传递值,然后就会写入到对应的csv文件中。

    但是在执行脚本之前,我们必须先创建一个csv文件,在linux上命令是:

    touch test.csv

    如下面图中所示,因为如果不提前创建文件,会报找不到这个文件的错误,如下面第二张图中所示:

    请点击输入图片描述

    请点击输入图片描述

    由此可见,open函数打开文件时,文件不存在的时候不会自动创建新的文件。test.csv文件创建完毕以后,就可以执行这个脚本了,命令是是:

    python csv_scritps.py

    执行完毕后,打开csv文件,如下面所示:

    请点击输入图片描述

    从打开的test.csv文件中我们可以看到,第一次写入的值里['spam']*5是单独一列,['Baked Beans']是一列,而第二次写入的值里一个三个元素的列表是写了三列,这就说明,写入的时候,如果想对应值都是对其的,最好提前将他拼成指定长度的列表,而不能在writerow函数里拼接。

    请点击输入图片描述

    这里还可以出现的错误是,在open函数里没有带上'w'参数,代码如下面图中所示,这个时候如果直接执行脚本的话,会报错,not writeable,可见默认情况打开的csv文件对象是没有写权限的。

    请点击输入图片描述

    请点击输入图片描述

    根据上面遇到的错误信息和格式信息,我们新写了个脚本,如下所示:脚本中定义了一行表头字段,然后定义了一个三个子列表的列表,子列表中是和表头长度相同的元素。

    请点击输入图片描述

    然后删除旧的test.csv文件,命令是:

    rm test.csv

    然后执行脚本,命令是:

    python csv_scripts.py

    在查看执行后的结果,可以看到,数据就排列的相对整齐了。以上就是python将数据写入到csv的全部内容。

    请点击输入图片描述

    请点击输入图片描述

IO习题

 1.Java实现将九九乘法表输入到文本文件

public class Test1 {

         public static void main(String[] args) throws FileNotFoundException {

                   System.setOut(new PrintStream("table99.txt"));//重定项屏幕输出到ps对象中

                   for (int i = 1; i < 10; i++) {

                            for (int j = 1; j <= i; j++) {

                                     System.out.print(j + " * " + i + " = " + i * j +"\t");

                            }

                            System.out.println();

                   }

         }

}

2.从类似如下的文本文件中读取出所有的姓名,并打印出重复的姓名和重复的次数,

         并按重复次数排序,如果次数相同按姓名字母排序:

1,zhangsan,28

2,lisi,35

3,zhangsan,28

4,wangwu,35

5,zhangsan,28

6,lisi,35

7,zhaoliu,28

8,tianqi,35

class NameBean implements Comparable<NameBean> {

         // 名字

         private String name;

         // 出现次数

         private Integer count;

         public NameBean(String name, Integer count) {

                   super();

                   this.name = name;

                   this.count = count;

         }

         public String toString() {

                   return name + " 出现 " + count;

         }

 

         public int compareTo(NameBean bean) {

                   if (this.count > bean.count) {

                            return 1;

                   } else if (this.count < bean.count) {

                            return -1;

                   } else {

                            return this.name.compareTo(bean.name);

                   }

         }

}

 

public class Test2 {

         public static void readFile(File file) throws IOException {

                   Scanner sc = new Scanner(file);

                   Map<String, Integer> nameMap = new TreeMap<String, Integer>();

 

                   // 名字和重复次数的集合

                   Set<NameBean> nameSet = new TreeSet<NameBean>();

                   while (sc.hasNextLine()) {

                            String line = sc.nextLine();

                            String[] info = line.split(",");

                            String name = info[1];

                            if (nameMap.containsKey(name)) {

                                     int count = nameMap.get(name);

                                     nameMap.put(name, count + 1);

                            } else {

                                     nameMap.put(name, 1);

                            }

                   }

                   Set<Map.Entry<String, Integer>> entrys = nameMap.entrySet();

 

                   Iterator<Map.Entry<String, Integer>> it = entrys.iterator();

                   while (it.hasNext()) {

                            Map.Entry<String, Integer> entry = it.next();

                            nameSet.add(new NameBean(entry.getKey(), entry.getValue() - 1));

                   }

                   System.out.println(nameSet);

         }

 

         public static void main(String[] args) throws IOException {

                   readFile(new File("student.txt"));

         }

}

 

 

3.编写一个程序,将d:\java目录下的所有.java文件复制到d:\jad目录下,

         并将原来文件的扩展名从.java改为.jad。

public class Test3 {

         public static void copy(File src, File dest) throws IOException {

                   if (src == null || !src.exists()) {

                            System.out.println("源不存在");

                            return;

                   }

                   if (dest != null && !dest.exists()) {

                            dest.mkdir();

                   }

                   File[] fs = src.listFiles(new FilenameFilter() {

                            public boolean accept(File dir, String name) {

                                     return name.endsWith(".java");

                            }

                   });

                   OutputStream out = null;

                   InputStream in = null;

                   for (File f : fs) {

                            String oldName = f.getName();

                            StringBuilder newName = new StringBuilder();

                            newName.append(oldName.substring(0, oldName.lastIndexOf(‘.‘))).append(".jad");

                            in = new FileInputStream(f);

                            out = new FileOutputStream(dest.getPath() + File.separator

                                               + newName.toString());

 

                            byte[] buff = new byte[1024];

                            int len = 0;

                            while ((len = in.read(buff)) != -1) {

                                     out.write(buff, 0, len);

                            }

                            out.close();

                            in.close();

                   }

         }

 

         public static void main(String[] args) throws IOException {

 

                   File src = new File("d:/java");

                   File dest = new File("d:/jad");

                   copy(src, dest);

         }

}

 

4.从键盘读入一行字符串,这行字符串内容类似如下:"2,10,1,22,19,30";

         输入升序排序或者降序排序,然后根据输入打印排序结果

public class Test4 {

         public static void main(String[] args) {

                  

                   Scanner sc = new Scanner(System.in);

                   sc.useDelimiter("\n");

                   Set<Integer> set = new TreeSet<Integer>(new Comparator<Integer>() {

                            public int compare(Integer o1, Integer o2) {

                                     return o1.compareTo(o2) * -1;

                            }

                   });

                   while(sc.hasNextLine()){

                            set.clear();

                            String ele  = sc.nextLine();

                            String[] arr = ele.split(",");

                            for (String s : arr) {

                                     set.add(new Integer(s));

                            }

                            System.out.println("排序后= "+set);

                   }

                  

         }

}

5.删除一个目录(注意:要删除目录必须删除目录下的文件和子目录)

public class Test5 {

 

         public static void delDir(File dir) {

                   if (dir == null || !dir.exists()) {

                            return;

                   }

                   if (dir.isFile()) {

                            dir.delete();

                   } else {

                            File[] fs = dir.listFiles();

                            for (File f : fs) {

                                     delDir(f);

                                     if (dir.list().length == 0) {// 空目录

                                               dir.delete();

                                     }

                            }

                   }

         }

 

         public static void main(String[] args) {

                   File dir = new File("D:/jad");

                   delDir(dir);

         }

}

 

6.将一个文件中的内容倒序(不允许用第二个文件)

public class Test6 {

 

         public static void reverse(String file) {

 

                   int total = 0;// 读取的总字节数

                   char[] buff = new char[30];

                   try (Reader in = new FileReader(file);) {

 

                            int len = 0;

                            while ((len = in.read(buff)) != -1) {

                                     total += len;

                            }

                   } catch (Exception e) {

                   }

                   //==============

                   try (Writer out = new FileWriter(file);) {

                            for (int i = total - 1; i >= 0; i--) {

                                     out.write(buff[i]);

                            }

                   } catch (Exception e) {

 

                   }

 

         }

 

         public static void main(String[] args) {

                   // start哥曾信佛但佛信曾哥end

                   reverse("out.txt");

         }

}

 

7.public class GuessDemo {

         /**

          * 1.系统先一个生成[1,100]之间的随机数; 2.程序得到键盘录入的数据,要做检查

          */

         public static void guess() {

                   Integer ran = new Random().nextInt(100) + 1;// [1,100]

 

                   System.out.println("随机数= " + ran);

                   Scanner sc = new Scanner(System.in);

                   while (sc.hasNextLine()) {

                            String input = sc.nextLine();

                            // 检查input是否由数字组成

                            if (!input.matches("\\d+")) {

                                     System.out.println("亲,请输入数字");

                            } else {

                                     Integer num = new Integer(input);

                                     if (num > 100 || num < 1) {

                                               System.out.println("亲,请输入的[1,100]之间的数字");

                                     } else {

                                               // [1,100];

 

                                               switch (num.compareTo(ran)) {

                                               case 1:

                                                        // 此时num> ran

                                                        System.out.println("亲,你输入大了");

                                                        break;

                                               case -1:

                                                        System.out.println("亲,你输入小了");

                                                        break;

                                               default:

                                                        System.out.println("亲,恭喜你中奖了");

                                                        return;

                                               }

                                     }

                            }

                   }

         }

 

         public static void main(String[] args) {

                   guess();

         }

}

以上是关于如何用python将九九乘法表写入csv文件中?的主要内容,如果未能解决你的问题,请参考以下文章

如何用C#编写九九乘法表??

如何用javascript编写九九乘法表

如何用do…while循环输出九九乘法表?

如何用python做出倒写乘法口诀表?

如何用while循环 输出一个九九乘法表

编程输出如下形式的九九乘法表: