首页 > 编程语言 > 详细

一、python演示创建文件

时间:2020-03-26 10:19:36      阅读:108      评论:0      收藏:0      [点我收藏+]

一、python代码

技术分享图片

 代码如下:

 # 创建一个txt文件,文件名为mytxtfile,并向文件写入msg
def text_create(name, msg):
    desktop_path = "E:\\PyTest\\"  # 新创建的txt文件的存放路径
    full_path = desktop_path + name + .txt  # 也可以创建一个.doc的word文档
    file = open(full_path, w)
    file.write(msg)   #msg也就是下面的Hello world!
    # file.close()
 
text_create(mytxtfile, Hello world!)
# 调用函数创建一个名为mytxtfile的.txt文件,并向其写入Hello world!

二、C#调用python

1、搜索安装IronPython包

技术分享图片

 2、python调用

 项目->添加->新建文件夹,命名为PythonFiles,把Python脚本复制放在这个文件夹下

 添加两个引用,在IronPython包的根目录下面选择IronPython.dll和Microsoft.Scripting.dll

技术分享图片

 test.py

技术分享图片

 三、明确调用python是否成功

所以我们不是要通过调用python文件的方式而是直接调用python方法

技术分享图片

 代码如下:

        static void Main(string[] args)
        {
            //Non-ASCII character ‘\xe6‘ in file    加上#coding=UTF-8
            //默认文件保存路径
            string localPath = Path.Combine(Directory.GetCurrentDirectory(), "PythonFIles", "test.py");//获取应用程序的当前工作目录
            ScriptRuntime pyRuntime = Python.CreateRuntime();
            dynamic obj = pyRuntime.UseFile(localPath);

            Console.WriteLine(obj.text_create("mytxtfile", "Hello World!-python"));
            Console.ReadKey();
        }

 python代码如下:

#coding=UTF-8
# 创建一个txt文件,文件名为mytxtfile,并向文件写入msg
def text_create(name, msg):
    desktop_path = "E:\\PyTest\\"  # 新创建的txt文件的存放路径
    full_path = desktop_path + name + .txt  # 也可以创建一个.doc的word文档
    file = open(full_path, w)
    file.write(msg)   #msg也就是下面的Hello world!
    file.close()
    return msg
 
#text_create(‘mytxtfile‘, ‘Hello world!‘)
# 调用函数创建一个名为mytxtfile的.txt文件,并向其写入Hello world!

 

一、python演示创建文件

原文:https://www.cnblogs.com/fger/p/12571963.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!