2014-05-13 34 views
2

我使用這個Python腳本版權高談闊論添加到所有的開始我的C#腳本添加一個文本文件,我的代碼開始引起

import re 
import shutil 
import os 

copyrightloc = 'C:/DATA/pyscripts/copyright.txt' 
rootdir = 'C:/DATA/pyscripts/02_CODE' 
dstdir = 'C:/DATA/pyscripts/codecopy' 

spielfile = open(copyrightloc, "r") 
spiel = spielfile.read() 

for subdir, dirs, files in os.walk(rootdir): 
    for file in files: 
     if file.endswith(".cs"): 
      with open(subdir+'/'+file, "r+") as codefile , open(dstdir+'/'+file, 'w') as destfile: 
       destfile.write(spiel+'\n' + codefile.read()) 

正如你看到的我是一個解析錯誤將原始字符串添加到版權字符串並將其寫入新文件。

這些文件在完成時看起來很好,但在每個文件中,在原始文件的第一行,我都會得到解析錯誤。例如,下面顯示了在版權speil和原始文件的開頭末尾的新文件的exerpt ...

  BLAH BLAH BLAH COPYRIGHT 
    * OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING 
    * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF 
    * CONTRACT, NEGLIGENCE, TORT OR OTHERWISE, ARISING OUT OF OR IN 
    * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE OR ITS DERIVATIVES. 
    */ 


using UnityEngine; [!!!ERROR IS SHOWN ON THIS LINE!!!] 
using System.Collections; 

public class Floop : MonoBehaviour { 

    public rot glorb; 
    public GameObject foo; 

       BLAH BLAH BLAH MY CODE 

我猜有一些無形的性格有類似的文件「結束「或什麼的,但我不能在記事本++中看到任何東西,當我選擇」顯示所有字符「...如果我去到有問題的行的開頭,點擊刪除錯誤消失.. 我怎樣才能讓我的Python腳本避免這個問題?

+4

「BLAH BLAH BLAH版權」沒有被註釋掉 – reggaeguitar

+0

您正在使用C風格的註釋在C# – stark

+0

什麼恰恰是你的語法錯誤? –

回答

5

MSDN C# style guide說你不應該在評論周圍使用星號塊。你可以嘗試在//前面加上版權的每一行嗎?

Alternatively,你可以(在每一行的開頭音符缺乏星號),使用此格式:

/* 
copyright here 
*/ 
0

有機會在您的版權文本有Unicode字符不正確編碼的嘗試使用的編解碼器模塊

import re 
import shutil 
import os 
import codecs 

copyrightloc = 'C:/DATA/pyscripts/copyright.txt' 
rootdir = 'C:/DATA/pyscripts/02_CODE' 
dstdir = 'C:/DATA/pyscripts/codecopy' 

spielfile = codecs.open(copyrightloc, "r", encoding="utf8") 
spiel = spielfile.read() 

for subdir, dirs, files in os.walk(rootdir): 
    for file in files: 
     if file.endswith(".cs"): 
      with codecs.open(subdir+'/'+file, "r+",encoding="utf8") as codefile , open(dstdir+'/'+file, 'w') as destfile: 
       destfile.write(spiel+'\n' + codefile.read()) 
+0

歡呼聲。我會很快嘗試這個(就像接下來的幾天),如果它有效,給你賞金 –

+0

我會用'io.open()'代替; 'codecs'模塊文件對象有一些錯誤,這是(更好的架構)'io'模塊不會受到的。 –

+0

此代碼**不起作用**除非您在編寫時再次編碼*! –

1

也許您的文件中包含一個「字節順序標記」,這在文件中表示編碼的開始是一些特殊字符。

如果您在預期的之前看到一些額外的字符,請使用HEX編輯器進行檢查。

如果是這種情況,那麼你應該使用'utf-8-sig'編碼。我不是一個Python的出口,但你的代碼看起來是這樣的

... 
spielfile = codecs.open(copyrightloc, "r", encoding="utf-8-sig") 
... 
with codecs.open(subdir+'/'+file, "r+", encoding="utf-8-sig") as codefile , open(dstdir+'/'+file, 'w', encoding="utf-8-sig") as destfile: 
相關問題