一、python演示创建文件

一、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!

猜你喜欢

转载自www.cnblogs.com/fger/p/12571963.html