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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM