2017-10-13 189 views
1

如何编辑CSV文件中的记录?编辑CSV记录

比如我有一个名为“test.csv”的.csv文件,其内部是:

 
"123","Active" 
"456","Not-Active" 
"999000123","Active" 

如何编辑"456"并从Not-Active改为Active

我的唯一方法可以想到它是:

  1. 打开.csv文件。也许将数据存储在一个字符串中?
  2. 搜索"456","
  3. 获取"456","的行位置。这个怎么做?
  4. 删除我们刚刚获得位置的行。这个怎么做?
  5. 重新创建我们想要的行。这个怎么做?
  6. 将重新创建的数据插入到行位置。这个怎么做?
  7. 保存.csv文件。

但是有没有更简单的方法来做到这一点?

如果不是,我该怎么做#4,5和6的步骤?

也许将它转换成一个数组或东西?但我不知道如何在Classic ASP中做到这一点。

+0

[打开,编辑和重新保存一个CSV文件(可能的重复https://stackoverflow.com/questions/19936645/open-edit-and-re- save-a-csv-file) – abr

+0

@abr没有那是删除重复的文本,但没有找到文本,然后编辑该文本右侧的文本。不一样,或者更糟糕,不是肯定的重复 – compcobalt

+0

您读取文件,以逗号分隔每行,如果第一个字段的值为“456”,则替换第二个字段的值,然后将数据写回文件。 –

回答

1

基于Ekkehards答案,这里是ASP版本。 .csv文件需要位于与.asp脚本相同的目录中。随意授予点Ekkehard

<%@LANGUAGE="VBSCRIPT"%> 
<% option explicit %> 

<% 
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject") 
Dim tsIn : Set tsIn = goFS.OpenTextFile(Server.MapPath("46734115.csv")) 
Dim tsOut : Set tsOut = goFS.CreateTextFile(Server.MapPath("46734115-2.csv")) 
Dim sLine 
Do Until tsIn.AtEndOfStream 
    sLine = tsIn.ReadLine() 
    dim pos : pos = instr(sLine, """456"",") 
    Response.Write(pos) 
    if pos > 0 then 
     ' to keep things simple, just replace the whole line 
     sLine = """456"",""Active""" 
    end if 
    tsOut.WriteLine sLine 
    ' Just so there is something to see: print line to the browser window 
    Response.Write(sLine & "<br />") 
Loop 
tsOut.Close 
tsIn.Close 
%> 
1

一个simplyfied版本script @abr mentioned的:

Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject") 
Dim tsIn : Set tsIn = goFS.OpenTextFile("..\data\46734115.csv") 
Dim tsOut : Set tsOut = goFS.CreateTextFile("..\data\46734115-2.csv") 
Dim sLine 
Do Until tsIn.AtEndOfStream 
    sLine = tsIn.ReadLine() 
    WScript.Echo "<", sLine 
    If "456," = Left(sLine, 4) Then 
     sLine = "789,""something else""" 
    End If 
    WScript.Echo ">", sLine 
    tsOut.WriteLine sLine 
    WScript.Echo  
Loop 
tsOut.Close 
tsIn.Close 

输出:

type ..\data\46734115.csv 
123,"Active" 
456,"Not-Active" 
999000123,"Active" 

cscript 46734115-3.vbs 
< 123,"Active" 
> 123,"Active" 

< 456,"Not-Active" 
> 789,"something else" 

< 999000123,"Active" 
> 999000123,"Active" 

type ..\data\46734115-2.csv 
123,"Active" 
789,"something else" 
999000123,"Active" 
+0

更容易工作我收到一个错误:Microsoft VBScript运行时错误'800a01a8'需要的对象:'WScript'。我试图添加WScript.CreateObject(“WScript.Shell”),但没有帮助 – compcobalt

+0

我试图用'Response.write替换WScript.Echo,但没有奏效。关于我错过什么的任何输入? – compcobalt